3

我在使用 sigchld 时遇到了一些麻烦...

我想要做的是用fork创建一个子进程并使子进程打印并休眠几次......在这些过程中我想向孩子发送信号(SIGSTOP和SIGCONTINUED)并且我想要父母打印信号是什么......这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
void handler (int i) {
    int x;
    waitpid(-1,&x, 0);
    printf("WIFSTOPPED=%d, WIFCONTINUED=%d\n", WIFSTOPPED(x),WIFCONTINUED(x) );
}

int main(){

    int x;
    int q=fork();
    if(q==0){
        int i=0;
        printf("%d\n",getpid());
        while (i<20){
            printf("%d\n", i++);
            sleep(1);
        }
        _exit(0);
    }
    else {
        signal(SIGCHLD, handler);
        waitpid(-1,&x, 0);
        while(WIFEXITED(x)!=1){
            waitpid(-1,&x, 0);
            sleep(1);
        }
        exit(0);
    }
}

但它不起作用,因为当我向孩子发送 SIGSTOP 或 SIGCONTINUED 时,孩子停止并继续但父母不打印任何东西

有什么建议吗?

4

1 回答 1

1

您的处理程序不应waitpid再次调用,并且您的 main while 循环也不正确:您再次调用waitpid了两次第一次。最后,您的waitpid电话多声明对状态更改(WUNTRACED选项)感兴趣。

一个非常正确的代码可能是:

void handler (int i) { // a handler just handle the fact some signal occured
    printf("in handler\n");
}

int main(){
    int x;
    int q=fork();
    if(q==0){
        int i=0;
        printf("%d\n",getpid());
        while (i<20){
            printf("%d\n", i++);
            sleep(1);
        }
        _exit(0);
    }
    else {
        signal(SIGCHLD, handler); // catch child status changes
        do {
            waitpid(-1,&x, WUNTRACED|WCONTINUED); // wait until child terminates or changes its status
            if (WIFSTOPPED(x)|WIFCONTINUED(x)) // test what really happens
                printf("STOPPED=%d, CONTINUED=%d\n", WIFSTOPPED(x),WIFCONTINUED(x) );
        } while(!WIFEXITED(x));
        exit(0);
    }
}
于 2014-12-07T11:44:20.177 回答