简体   繁体   中英

Father process was block while set SIGCHLD

This is my code, I had simplified it.

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

void signal_handle(int sig)
{
    int status;
    wait(&status);
}

int main()
{
    pid_t pid = fork();

    if (pid > 0)
        signal(SIGCHLD, signal_handle);
    if (pid == 0) {
        if (execl("/bin/ls", "/", (char *)0) < 0)
        {
            perror("execl");
            return -1;
        }
    }
    return 0;
}

When I run it, I found that, son process print the run result, but father process was blocked.

what should I do, if a father has much son process? set wait(&status) for every one?

I'm very sorry for my bad english!

I don't see why the parent process would hang, and it doesn't on my machine.

After the fork() , the parent process invokes signal() to set the signal handler and immediately exits. The child, meanwhile, executes ls to print the contents of the current directory (because the "/" argument becomes argv[0] , the program name, and there are no additional arguments). It then exits too. Except under very unlikely circumstances, the parent has exited long before the child completes.

If you want the parent process to wait until it gets the 'death of a child' signal, add a call to pause() in the parent-only execution path:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

static void signal_handle(int sig)
{
    int status;
    pid_t pid = wait(&status);
    printf("%d: signal %d child %d status 0x%.4X\n", (int)getpid(), sig, (int)pid, status);
}

int main(void)
{
    pid_t pid = fork();

    if (pid > 0)
    {
        signal(SIGCHLD, signal_handle);
        pause();
    }
    else if (pid == 0)
    {
        execl("/bin/ls", "ls", "/", (char *)0);
        perror("execl");
        return -1;
    }
    else
        perror("fork");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM