1

在一门课程中,老师给了我们一些代码(在黑板上),但他的字迹很糟糕,我无法做出几个部分。在管道和叉子上也是新的,所以这无济于事。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
void main () {
    int a[] = {1,2,3,4}, f[2];  // ok so we initialize an array and a "pipe folder" (pipefd in manual) ?
    pipe (f);                   // not 100% sure what this does ?
    if (fork () == 0) {         // if child
        close (f[0]);               // close pipe read-end
        a[0] += a[1];               
        write (f[1], &a[0], sizeof (int))      // fixed
        close (f[1]);               // close pipe write-end
        exit(0);                    // closes child and sends status update to parent ?
    }
    else {                          // if parent
        close (f[1])                // close write-end of pipe
        a[2]+=a[3];
        read (f[0], &a, sizeof(int))          // fixed
        wait (0);                   // waits for child to ... close ? or just finish ? or is it the same thing
        a[0]+= a[2]; close (f[0]); 
        printf ("%d\n, "a[0]);
   }
}

孩子和父母是否按特定顺序进行。我猜父母等待孩子关闭,如果close (f[1])没有返回错误,它会继续吗?(顺便说一句,“0”代表什么wait(0))然后才继续?

我有什么误解?我做对了吗?

我想我应该提到我做了一些研究,man但我发现它非常令人困惑。就我而言,它们适用于已经知道自己在做什么但忘记了一些细节(例如要包括什么以及 -p 做什么)的用户,或者是对基本了解有更多了解的人。

4

1 回答 1

5
  1. pipe创建两个文件描述符。一个是你写的,另一个是你读的。你写到一个,你可以从另一个读取。UNIX 中的文件描述符是整数 ( int)。
  2. 文件描述符由子进程继承。因此,管道使人们能够在进程之间进行通信。在这种情况下,孩子会写入一些父母可以读取的数据
  3. 不要在读/写中使用 8 ,而是使用sizeofie sizeof(int)。编译将为存储的字节数提供正确的值,并且int
  4. wait(0)等待孩子终止。
于 2012-06-07T18:30:50.490 回答