收获僵尸进程 – 孩子

我正在从父到子的主要命令行参数和计数和打印。 我的问题是,我不确定我是否正在收割孩子? 我不只是需要退出0或者我需要再次调用fork吗?

#include  #include  #include  #include  #include  int main(int argc, char *argv[]) { int length = 0; int i, n; int fdest[2]; // for pipe pid_t pid; //process IDs char buffer[BUFSIZ]; if ((pid = fork()) < 0) /* attempt to create child / parent process */ { printf("fork error"); } if (pipe(fdest)  0) { close(fdest[0]); for(i = 1; i < argc; i++) /* write to pipe */ { write(fdest[1], argv[i], strlen(argv[1])); } } else { /* child Process */ close(fdest[1]); for(i = 1; i < argc; i++) { length +=( strlen(argv[i])); /* get length of arguments */ } n = read(fdest[0], buffer, length); printf("\nchild: counted %d characters\n", n); } exit(0); } 

不,你没有正确收获孩子。 在您的情况下,如果子进程在父进程退出之前完成,则子进程将变为僵尸。 然后,当父进程完成时,子进程将被重新设置为init (无论是已完成并且是僵尸,还是仍在运行)。 init然后为你收割孩子。

要收获孩子,请在exit前添加对wait()的调用。

顺便说一句,你有另一个错误 – 你在fork 之后创建管道,所以父和子都创建了一个(不同的)管道 – 它们没有连接。 移动if (pipe(...fork()之前向上if (pipe(...