簡體   English   中英

UNIX信號處理。 在SIGCHLD處理程序中等待。 C

[英]UNIX signal handling. Wait in SIGCHLD handler. C

我有一個父母和一個孩子的過程。 在父級中,我為SIGCHLD建立了信號處理程序。 我將SIGTSTP信號發送給子級,該子級觸發SIGCHLD並在父級的SIGCHLD siganl處理程序中調用調用函數以獲取已停止子級的狀態。 但它不會立即返回,而是會阻塞。 然后,我向孩子發送一個SIGCONT信號,並等待將errno設置為Interuppted系統調用返回。 我不明白我在想什么。

pid_t pid;


static void sig_chld(int signo);


int main() {

    struct sigaction act, savechld;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;


    act.sa_handler = sig_chld;
    if (sigaction(SIGCHLD, &act, &savechld) < 0){
        return errno;
    }

    pid = fork();
    switch (pid){
        case -1:{
            perror("fork failed");
            return errno;
        }
        case 0:{    //child
            if (sigaction(SIGCHLD, &savechld, NULL) < 0)
                return errno;

            execlp(path, name_of_executable, (char*)NULL);
            return errno;
        }
        default:{
            for (;;)
                pause();
        }
    }
    return 0;
}



void sig_chld(int signo) {
    int statol;
    if (wait(&statol) < 0){
        perror("waitt error");
        exit(errno);
    }

    if (WIFSTOPPED(statol)){
        puts("Child is stopped");
    } else if (WIFEXITED(statol)){
        puts("Child exited");
    } else if (WIFCONTINUED(statol)){
        puts("Child continued");
    } else if (WIFSIGNALED(statol)){
        puts("Child is signaled");
        int sig = WTERMSIG(statol);
        psignal(sig, NULL);
    }
}

您必須使用waitpid()而不是wait() ,並且需要指定選項WUNTRACED來停止使用waitpid()報告的子項,如下所示:

if (waitpid(-1, &statol, WUNTRACED) < 0) {

現在, waitpid()應該立即返回,並且您的宏WIFSTOPPED(&statol)應該為true。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM