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
384 views
in Technique[技术] by (71.8m points)

c - Why child process not getting exited before parent process calls wait() function?

I'm working on c program which uses fork() and wait() calls, firstly I created five child processes and then I called wait() for five times. Whenever I execute the program it prints the same child process id in the second for loop which is displayed from the first for loop. The child processes were never getting exited before the wait() function is getting called. Why is this happening? Why the cpid is always printing the exact child process id which were displayed before?

code :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main( )
{
    int child_pids[5];
    int i;
    printf("PARENT ID: %d 
", getpid());
    for(i=0;i<5;i++) {
        if(fork()==0) {
            printf("child(pid): %d of parent(pid): %d 
",getpid(),getppid());
            exit(0);
        }
    }
    for(i=0;i<5;i++) {
        int cpid=wait(NULL);
        printf("parent (pid): %d waited for child(pid): %d 
",getpid(),cpid);
    }
    return 0;
}

If there are any mistakes in my way of asking questions, please comment below

question from:https://stackoverflow.com/questions/65845325/why-child-process-not-getting-exited-before-parent-process-calls-wait-function

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

1 Reply

0 votes
by (71.8m points)

Upon exit, the child leaves an exit status that should be returned to the parent. So, when the child finishes it becomes a zombie.

Whenever the child exits or stops, the parent is sent a SIGCHLD signal. The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child.

If the parent exits, than you can see your children still as zombie processes (unwaited children ).

wait() just tells you which child exited so you can get the exit code. If you have more children running, then of course, others could have terminated in the meantime as well.

If you don't care about the exit status, then wait() is just fine, but you still have to wait on all children you started.


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

...