pause()/ kill()父/子进程。父母在获得第一个SIGTERM之后不断从孩子那里获得SIGTERM

时间:2019-04-25 10:43:34

标签: c signals fork kill pause

我要做的是创建一个子进程,该子进程在就绪时(完成某些任务之后)将信号发送给父进程。发送信号后,父级将保持不暂停状态并进行一些工作,然后再次暂停以等待子级准备就绪。发送信号后的孩子会阻塞并等待我的输入,然后再向父进程发送另一个信号。

我希望重复执行任意次。下面是我的方法:

void sig_handler(int sig){
        if (sig == SIGTERM) printf("Working team is ready!\n");
        return;
}

int main(){
        //signal(SIGTERM,sig_handler);
        char*** orders;
        int NumOrders;
        if ((orders = importFileToArray(&NumOrders)) != NULL){
                SDFSort(orders, NumOrders);
                int i,j;
                for (i=0;i<NumOrders;i++){
                        for (j=0;j<4;j++){
                                printf("%s ", orders[i][j]);
                        }
                        printf("\n");
                }

                pid_t pid, ppid = getpid();

                if ((pid = fork()) == 0){
                        int choice = 1;
                        while(1){
                                sleep(1);
                                kill(getppid(),SIGTERM);
                                //do some work
                                scanf("%d", &choice);
                        }
                }else{
                        while(1){
                                signal(SIGTERM,sig_handler);
                                pause();
                                //do some work
                        }
                        wait(NULL);
                }

        }
}

下面是输出:

Working team is ready!
a
Working team is ready!
Working team is ready!
Working team is ready!
Working team is ready!
Working team is ready!
a
Working team is ready!
Working team is ready!
a
Working team is ready!
Working team is ready!
Working team is ready!
Working team is ready!
^C

如您所见,它第一次运行良好(父级阻止。子级发送带有“工作团队已准备就绪”消息的信号,父级取消阻止。但是,而不是在scanf上阻止,似乎孩子不顾自己的输入而不断向父母发送信号。我在做什么错了?

0 个答案:

没有答案