Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

c - Reaping zombie process - child

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 0 or 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("
child: counted %d characters
", n);

}
exit(0);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...