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

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 系统调用的 return 值吗?

修改后的代码片段应该看起来像

    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);
    }