【发布时间】:2019-03-17 15:00:27
【问题描述】:
我现在正在为我的系统编程课程学习 Linux 和管道,我现在很难理解在管道数组中关闭文件描述符。
// write the code to loop over the command line arguments (remember to skip the executable name)
for (int i = 1; i < argc; i++) {
// call pipe before we fork
if ((pipe(pipe_fd[i-1])) == -1) {
perror("pipe");
exit(1);
}
// call fork
int result = fork();
if (result < 0) { // case: a system call error
// handle the error
perror("fork");
exit(1);
} else if (result == 0) { // case: a child process
// child does their work here
// child only writes to the pipe so close reading end
if (close(pipe_fd[i-1][0]) == -1) {
perror("close reading end from inside child");
exit(1);
}
// before we forked the parent had open the reading ends to
// all previously forked children -- so close those
int child_no;
for (child_no = 0; child_no < i-1; child_no++) {
if (close(pipe_fd[child_no][0]) == -1) {
perror("close reading ends of previously forked children");
exit(1);
}
}
int len = strlen(argv[i]);
// write len to the pipe as an integer
if (write(pipe_fd[i-1][1], &len, sizeof(int)) != sizeof(int)) {
perror("write from child to pipe");
exit(1);
}
// I'm done with the pipe so close it
if (close(pipe_fd[i-1][1]) == -1) {
perror("close pipe after writing");
exit(1);
}
// exit so I don't fork my own children on next loop iteration
exit(0);
} else {
// in the parent but before doing the next loop iteration
// close the end of the pipe that I don't want open
if (close(pipe_fd[i-1][1]) == -1) {
perror("close writing end of pipe in parent");
exit(1);
}
}
}
我将列出我现在理解的内容:
- 我了解父子进程需要关闭那些不需要使用的 fd,在这种情况下子进程正在向父进程写入,因此父进程需要关闭写入端口,子进程需要关闭读取端口。
- 我了解文件描述符在父进程和子进程之间共享。
上面的代码是从我的演讲幻灯片中给出的,我特别对一件事感到困惑。
在循环中,我观察到,一旦这个孩子被 fork 创建,每个孩子都在关闭其阅读端口,执行此操作的代码是:
else if (result == 0) { // case: a child process
// child does their work here
// child only writes to the pipe so close reading end
if (close(pipe_fd[i-1][0]) == -1) {
perror("close reading end from inside child");
exit(1);
}
据我目前的理解是,每个孩子被fork生下来后都会关闭自己的阅读端口,我认为后面创建的孩子应该不担心关闭以前孩子的阅读端口。
但是看了这段代码后我的理解似乎不正确:
// before we forked the parent had open the reading ends to
// all previously forked children -- so close those
int child_no;
for (child_no = 0; child_no < i-1; child_no++) {
if (close(pipe_fd[child_no][0]) == -1) {
perror("close reading ends of previously forked children");
exit(1);
}
}
我不明白为什么后面的孩子要关闭以前的孩子的阅读端口,一旦这些孩子被创建,那些阅读端口不是已经关闭了吗?
感谢您帮助我。 :)
【问题讨论】:
-
管道的一端不会关闭,就另一端而言,直到它的 所有 描述符都关闭。当你 fork 时,新进程拥有所有父进程打开描述符的副本,并且需要关闭它不会使用的那些。
-
不是所有变量都被复制,文件描述符被共享吗?如果fds是共享的,关闭的效果是不是对所有进程都是透明的?
标签: c linux pipe system-calls