通过管道发送和接收信息?

Sending AND receiving information through pipes?

我试图更好地理解一个 parent 和多个 child 进程之间的管道,所以我制作了一个简单的程序来产生两个 child 进程,给它们一个值( i),让他们更改该值,然后将其打印出来。

但是它不起作用,因为程序打印 i 就好像它没有改变一样,并在 children 中打印改变的 i。我显然没有正确发送 i 变量,那么我应该如何解决这个问题?

int main ( int argc, char *argv[] ){
    int i=0;
    int pipefd[2];
    int pipefd1[2];
    pipe(pipefd);
    pipe(pipefd1);
    pid_t cpid;
    cpid=fork();
    cpid=fork();
    if (cpid ==0)  //this is the child
    {
        close(pipefd[1]);   // close write end of first pipe
        close(pipefd1[0]);  // close read end of second pipe
        read(pipefd[0], &i, sizeof(i));
        i=i*2;
        printf("child process i= %d\n",i);  //this prints i as 20 twice
        write(pipefd1[1],&i, sizeof(i));
        close(pipefd[0]); // close the read-end of the pipe
        close(pipefd1[1]);
        exit(EXIT_SUCCESS);
    } 
    else
    {
        close(pipefd[0]);   // close read end of first pipe
        close(pipefd1[1]);  // close write end of second pipe
        i=10;
        write(pipefd[1],&i,sizeof(i));  
        read (pipefd1[1], &i, sizeof (i));
        printf("%d\n",i); //this prints i as 10 twice
        close(pipefd[1]);
        close(pipefd1[0]);
        exit(EXIT_SUCCESS);
    }
}

主要问题是您没有创建两个 child 进程。您正在创建三个。

cpid=fork();
cpid=fork();

第一个 fork 导致创建 child 进程。此时,child 和 parent 都执行下一条语句,也是 fork。所以 parent 创建了一个新的 child 而第一个 child 也创建了一个 child。这就是为什么所有东西都打印两次的原因。

您需要在执行任何其他操作之前立即检查 fork 的 return 值。

如果您要删除其中一个 fork 调用,您仍然会在 parent 中得到错误的 i 值。那是因为它从管道的错误一端读取。

child 正在写入 pipefd1[1],但 parent 也在尝试从 pipefd1[1] 读取。它应该从 pipefd1[0].

读取

编辑:

删除了假设管道是双向的错误示例代码,而事实并非如此。