我从父级到子级将命令行参数传递给main并对其进行计数和打印。我的问题是我不确定我正在收养孩子吗?我不需要出口0
还是我需要再次打电话给fork?
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
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) /* attempt to create pipe */
printf("pipe error");
/* parent process */
else if (pid > 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);
}
最佳答案
不,您没有正确收养孩子。在您的情况下,如果子进程在父进程退出之前完成,则子进程将成为僵尸。然后,当父进程完成时,子进程将重新绑定(bind)到init
(它是否已完成并且是僵尸,还是仍在运行)。 init
然后为您收获孩子。
要收获孩子,请在wait()
之前添加对exit
的调用。
顺便说一句,您还有另一个错误-您在fork
之后创建了管道,因此父级和子级都创建了一个(不同的)管道-它们没有连接。将if (pipe(...
上移到fork()
之前。