简体   繁体   English

设置SIGCHLD时,父进程被阻止

[英]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? 为每一个设置wait(&status)

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. fork() ,父进程调用signal()来设置信号处理程序并立即退出。 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). 同时,该子进程执行ls来打印当前目录的内容(因为"/"参数变为argv[0] ,即程序名称,并且没有其他参数)。 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: 如果希望父进程等待直到收到“孩子死亡”信号,请在仅父级的执行路径中添加对pause()的调用:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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