本文介绍了收获僵尸进程 - 孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以命令行参数主要来自父母的孩子,他们的计算和打印。我的问题是,我不能保证我收获了孩子?不,我只是需要一个退出0
或者我需要再次调用fork?

 的#include< SYS / wait.h>
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;
#包括LT&;&string.h中GT;INT主(INT ARGC,CHAR *的argv [])
{INT长度= 0;
INT I,N;INT fdest [2]; //管道
将为pid_t PID; //进程ID
字符缓冲区[BUFSIZ];
如果((PID =叉())小于0)/ *试图创建子/父进程* /{
    的printf(叉错误);
}如果(管道(fdest)小于0)/ *尝试建立管* /
    的printf(管子错误);/ *父进程* /
否则如果(PID大于0){
    关闭(fdest [0]);    对于(i = 1; I< ARGC,我++)/ *写*管材/
    {
        写(fdest [1],ARGV [I],strlen的(ARGV [1]));
    }}其他{    / *子进程* /
    关闭(fdest [1]);    对于(i = 1; I< ARGC,我++)
    {
        长度+ =(strlen的(的argv [I])); / *参数获取长度* /
    }    N =读(fdest [0],缓冲液,长度);
    的printf(\\ nchild:计%d个字符\\ n,N);}
出口(0);
}


解决方案

没有,你是不是正确地收获着孩子。你的情况,如果子进程的父进程退出之前完成,孩子就会变成僵尸。然后,当父过程完成后,孩子将被重设父为的init (是否已完成,是一具僵尸,或仍在运行)。 的init 然后收获孩子给你。

要获得孩子,加一个调用等待()退出

顺便说一句,你有另一个错误 - 你创建的管道的之后的的,所以家长和孩子都可以创建一个(不同)管 - 他们没有连接。移动如果(管(... 叉前()

I am taking command line arguments to main from parent to child and counting them and printing. My question is that i am not sure that i am reaping the child? dont i just need an exit 0or do i need to call fork again?

#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);
}
解决方案

No, you are not reaping the child correctly. In your case, if the child process finishes before the parent process exits, the child will become a zombie. Then, when the parent process finishes, the child will be reparented to init (whether it has finished and is a zombie, or is still running). init is then reaping the child for you.

To reap the child, add a call to wait() before exit.

By the way, you have another bug - you are creating the pipe after the fork, so the parent and child each create a (different) pipe - they're not connected. Move the if (pipe(... up before the fork().

这篇关于收获僵尸进程 - 孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:34