c - 管道/ fork 有问题。说明书看不懂一半(man)

标签 c fork pipe

在一门类(class)中,老师给了我们一些代码(在粉笔板上),但他的字迹很糟糕,我无法拼出几个部分。管道和 fork 也是新的,所以这无济于事。

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

child 和 parent 是否按某种特定顺序前进。我猜 parent 会等待 child 关闭,如果 close (f[1]) 没有返回任何错误它会继续吗? (顺便说一下,wait(0) 中的“0”代表什么)然后才继续?

我误会了什么?我做对了吗?

我想我应该提到我使用 man 做了一些研究,但我发现它非常困惑。 就我而言,它们适用于已经知道自己在做什么但忘记了一些细节(比如要包含什么和 -p 做什么)的用户,或者只了解基本知识的用户。

最佳答案

  1. pipe 创建两个文件描述符。一个是你写的,另一个是你读的。你写进一个,你可以从另一个读取。 UNIX 中的文件描述符是整数 (int)。
  2. 文件描述符由子进程继承。因此,管道使人们能够在进程之间进行通信。在这种情况下, child 写了一些数据,然后 parent 可以读取
  3. 不要在读/写中使用 8,而是使用 sizeofsizeof(int)。编译将为存储的字节数和 int
  4. 提供正确的值
  5. wait(0) 等待子进程终止。

关于c - 管道/ fork 有问题。说明书看不懂一半(man),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937600/

相关文章:

c++ - Netbeans C/C++ 项目中的代码相同但输出不同

c - 为什么我 fork 的进程将 systemd 作为它们的父进程?

c - 如何使用管道运行命令?

C - 返回指向数组的指针

c++ - 锁定文件,使其无法删除

c - 不同日期时间字符串的相同mktime()结果

c - 使用两个子进程在我自己的 shell 中实现管道

linux - 在 linux 中,使用 pipe() 从 fork 进程调用 system()

python - Sage/Python 中 fork 后出现 SIGILL

sockets - 我应该在哪个时刻使用哪种进程间通信(ipc)机制?