简体   繁体   中英

Don't send SIGINT on CTRL+C to child processes but don't ignore the signal itself

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM