问题
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.
Before fork()
-ing, in the main process I call:
sigaction(SIGINT, &the_handler, NULL);
Where the_handler
stores the reference of a simple print function.
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?
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?
回答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: 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.
来源:https://stackoverflow.com/questions/48265494/dont-send-sigint-on-ctrlc-to-child-processes-but-dont-ignore-the-signal-itsel