繁体   English   中英

通过管道的进程间通信发送结构

[英]Interprocess communication sending structure via pipe

我必须显示使用管道运行命令所用的时间,所以我使用 gettimeofday 函数并通过管道传递指针,但是当我在父进程中读取它时,我得到了与预期不同的结果。 我应该得到 1604626608037896 但我有这个 94762421350317。这是我的代码:

    if (pipe(p) < 0)
        exit(1);
    pid=fork();
    if (pid == -1){
        printf("can't fork, error occured\n");
        exit(EXIT_FAILURE);
    }else if (pid == 0){
        //This is the child I get the time 
        gettimeofday(&current,NULL);
        //I write it in the pipe, if I print the time here i get the result I want
        write(p[1], &current, sizeof(current));
        close(p[1]);
        //then I execute the command
    }else{
        //this is the parent
        if (waitpid(pid, &status, 0) > 0){
            close(p[1]);
            struct timeval inicio;
            //Here is the problem I think, once I tried to read it I get a random number
            read(p[0], &inicio, sizeof(inicio));
            printf(": %ld,%ld\n", inicio.tv_sec,inicio.tv_usec); 
            
        }else{
            printf("waitpid() failed\n");
        }
        exit(0);
    }

我相信您期望if块在子进程中运行, else块在父进程中运行,并且在代码段之前调用fork 在这种情况下,两个进程中的p对于两个进程是不同的,并且它们没有连接。

如果抛出错误,您的read调用。 你能检查read系统调用的返回值吗?

剪下的修改后的代码应该看起来像

    if (pipe(p) < 0)
        exit(1);
    if (fork() < 0)
        exit(1);
    if (pid == 0){
        //I get the time 
        gettimeofday(&current,NULL);
        //I write it in the pipe, if I print the time here i get the result I want
        if (write(p[1], &current, sizeof(current)) < 0) {
            perror("write");
            exit(1);
        }
        close(p[1]);
        //then I execute the command
    }else{
        if (waitpid(pid, &status, 0) > 0){
            close(p[1]);
            struct timeval inicio;
            //Here is the problem I think, once I tried to read it I get a random number
            if (read(p[0], &inicio, sizeof(inicio)) < 0) {
                perror("read");
                exit(1);
            }
            printf(": %ld,%ld\n", inicio.tv_sec,inicio.tv_usec); 
            
        }else{
            printf("waitpid() failed\n");
        }
        exit(0);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM