总共有多少读或写文件描述符?

How many read or write file descriptors will be there in total?

main() {
    int fd1[2],fd2[2];
    pipe(fd1);
    pipe(fd2);
    fork(); 
    fork();
}

上面的代码总共会有多少个读写文件描述符?总共会创建多少个管道?哪些数据将从各自的父进程复制到子进程?也请解释一下程序的工作原理。

第一个 fork(); 创建一个 child;第二个 fork(); 是父亲 运行 和 child,所以你得到第二个 child 和一个盛大 child。所以总共有 4 个进程。

每个进程有 7 个打开的 FD:0,1,2 加上 fd1[0,1] 加上 fd2[0,1])。因此有 7 次 4 = 28 打开的 fds。

请注意,在不检查 error/child/father 的情况下调用 fork 是一个非常糟糕的主意!

查看使用 lsof -p <pid> 的 4 个 运行ning 进程之一的输出:

a.out   13147 thiel    0u   CHR  136,1      0t0       4 /dev/pts/1
a.out   13147 thiel    1u   CHR  136,1      0t0       4 /dev/pts/1
a.out   13147 thiel    2u   CHR  136,1      0t0       4 /dev/pts/1
a.out   13147 thiel    3r  FIFO    0,8      0t0 1143532 pipe
a.out   13147 thiel    4w  FIFO    0,8      0t0 1143532 pipe
a.out   13147 thiel    5r  FIFO    0,8      0t0 1143533 pipe
a.out   13147 thiel    6w  FIFO    0,8      0t0 1143533 pipe