如何向特定的孩子发送信号让它结束

时间:2014-01-06 22:09:23

标签: c linux

这是代码,我运行它但是所有三个孩子都自己结束了,但我在代码中指定SIGTERM只发送到第三个。

信号处理程序非常简单:

====================================================
void stop_handler(int signal_num)
{
         printf("Signal %d is received \n", signal_num);
}
====================================================

在main()中我创建了3个进程:

====================================================
       for (i = 0; i < 3; i++) {
                if( (pids[i] = fork()) < 0 ) {
                        printf("Fork failed!\n");
                        exit(2);
                } else if (pids[i] == 0) {
                        exit(do_childwork(i + 1));
                } else {
                        active_children++;
               }
        }
====================================================

do_childwork的主体是这样的:

====================================================
int do_childwork(int i)
{
        for (int j = 0; j < 3; j++) {
                if(signal(SIGTERM, stop_handler) == SIG_ERR) {
                        printf("signal install error\n");
                } else {
                        printf("Killed by parent\n");
                        return i * 5;
                }

                printf("sleeping %d for not getting signal\n", j);
                sleep(2);
        }
        return i * 3;

}
====================================================

并且在main()中仅发送到第3个进程:

====================================================
               printf("Sending signal to: %d\n", pids[2]);
               kill(pids[2], SIGTERM);
====================================================

但是当我运行它时,3个进程立即被杀死。

从输出中我可以告诉我将信号发送到正确的子进程。我编写了信号处理程序以及从谷歌搜索发出进程信号的方式。那么我做错了什么以及如何纠正它们?

1 个答案:

答案 0 :(得分:2)

您不需要多次安装信号处理程序。只需在信号处理程序中使用一个标志,并在设置标志时退出循环,即

static int flag = 0;

void stop_handler(int signal_num)
{
         printf("Signal %d is received \n", signal_num);
         flag = 1;
}

...

int do_childwork(int i)
{
        if(signal(SIGTERM, stop_handler) == SIG_ERR) {
                printf("signal install error\n");
                exit(1);
        }

        while (!flag) {
                printf("sleeping %d for not getting signal\n", j);
                sleep(2);
        }

        return i * 3;

}