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

1

2

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?

Interpenetrate answered 15/1, 2018 at 14:59 Comment(1)
That is somewhat of an x/y-question. You apparently don't want to change reception of the signal in the childs, but rather prevent the terminal session sending SIGINT from a Ctrl<C> keypress to the childs. That's done using setsidor daemonEnwind
J
3

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://mcmap.net/q/2036896/-linux-difference-between-forking-twice-and-daemon-ise

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.

Jae answered 15/1, 2018 at 15:15 Comment(3)
It kind of works simply if I fork() only once and call setsid() in child process. Am I missing something?Interpenetrate
@EmilTerman The setsid is what prevents the signals from being propagated. The dual fork is what stops the grand parent from having to wait for the grandchildren, otherwise, if the parent process exits, when the children exit, they become zombies.Jae
if the parent process exits, parent of the children will become init, so they will not become zombies.Ballyrag

© 2022 - 2024 — McMap. All rights reserved.