Skip to content
Advertisement

How to make parent process invoke wait when child exits with parent unblocked in Linux?

Here is an example, waitpid system call will block parent process until child process exits:

    pid_t pid = fork();
    if (pid < 0) {
        printf("errorn");
        return -1;
    } else if (pid == 0) {
        printf("childn");
        do_sonmething_in_child();
    } else {
        int status;
        waitpid(pid, &status, 0);
        printf("waitpid returned,do something elsen");
        do_something_else();
    }

What I want to achieve is parent process won’t be blocked, this can be done by using signal, so I changed my code:

void handler(int n) {
    printf("handler %dn", n);
    int status;
    wait(&status);
}
pid_t pid = fork();
if (pid < 0) {
    printf("errorn");
    return -1;
} else if (pid == 0) {
    printf("childn");
    do_sonmething_in_child();
} else {
    int status;
    signal(SIGCHLD, handler);
    do_something_else();
}

But another problem comes, if child exit before signal(SIGCHLD, handler), child will be a zombie, we can’t expect the child exit after signal(SIGCHLD, handler) is invoked, so, how to solve my problem?

Advertisement

Answer

You can set the signal handler before the fork () call.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement