不要将CTRL + C上的SIGINT发送给子进程,但不要忽略信号本身 [英] Don't send SIGINT on CTRL+C to child processes but don't ignore the signal itself

查看:93
本文介绍了不要将CTRL + C上的SIGINT发送给子进程,但不要忽略信号本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个任务控制程序,非常类似于Supervisor.

I'm trying to write a Task control program, very much like Supervisor.

我从配置文件中运行一些程序,并让它们在后台运行,而在主要过程中,我读取并执行其他命令.

I run some programs from a config file and let them run in the background, while in the main process I read and execute other commands.

fork() -ing之前,在主要过程中,我调用:

Before fork()-ing, in the main process I call:

sigaction(SIGINT, &the_handler, NULL);

the_handler 用于存储简单打印功能的引用.

Where the_handler stores the reference of a simple print function.

当按下CTRL + C时,子进程也被中断(我不希望这样做).我可以在派生子进程后运行: signal(SIGINT,SIG_IGN); 来忽略它,但我希望仍然能够在bash中运行此命令: $ kill -n2< child_pid> ,意思是我不想忽略它,对吧?

When CTRL+C is pressed, the child processes are interrupted as well (which I don't want). I could run: signal(SIGINT, SIG_IGN); after fork in child process to ignore it, but I would like to still to be able to run this command in bash: $ kill -n 2 <child_pid>, meaning, I don't want to ignore it, right?

那么,如何忽略从CTRL + C到子进程的SIGINT,但仍然能够以其他方式接收信号?还是我错过了什么?

So, how to ignore SIGINT from CTRL+C to child processes, but still be able to receive the signal in other ways? Or am I missing something?

推荐答案

执行此操作的传统方法是分叉两次.祖父母分叉其子女,然后等待他们.然后,每个孩子叉起来并立即离开.因为他们的父母已经退出,所以大孩子成为pid 1的父母.因此,发送给大父母的信号不会传播到前大孩子.

The traditional means of doing this is to fork twice. The grand parent forks its children and then waits for them. Each child then forks and exits straight away. Because their parents have exited, the grand children become parented by pid 1. Thus signals sent to the grand parent do not get propagated to the ex-grand children.

有关更多详细信息,请参见此答案

See this answer for a bit more detail

https://stackoverflow.com/a/26418006/169346

ETA:您需要在两个分支之间调用 setsid()孙子与父孙仍在同一进程组中,并且仍会收到有关孙子的信号父母会收到.

ETA: You need to call setsid() between the two forks otherwise the grandchild is still in the same process group as the grand parent and will still receive signals that the grand parent receives.

这篇关于不要将CTRL + C上的SIGINT发送给子进程,但不要忽略信号本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆