簡體   English   中英

設置SIGCHLD時,父進程被阻止

[英]Father process was block while set SIGCHLD

這是我的代碼,我已經簡化了它。

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

當我運行它時,我發現,子進程打印了運行結果,但是父進程被阻止了。

如果父親有很多兒子,我該怎么辦? 為每一個設置wait(&status)

我為我的英語不好對不起!

我看不到為什么父進程會掛起,並且它不在我的計算機上。

fork() ,父進程調用signal()來設置信號處理程序並立即退出。 同時,該子進程執行ls來打印當前目錄的內容(因為"/"參數變為argv[0] ,即程序名稱,並且沒有其他參數)。 然后它也退出。 除非在極不可能的情況下,否則父母在孩子完成學業之前就已經退出了。

如果希望父進程等待直到收到“孩子死亡”信號,請在僅父級的執行路徑中添加對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