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?

Emil Terman
  • 526
  • 4
  • 22
  • 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 keypress to the childs. That's done using `setsid`or `daemon` – tofro Jan 15 '18 at 15:22

1 Answers1

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://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.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • It kind of works simply if I `fork()` only once and call `setsid()` in child process. Am I missing something? – Emil Terman Jan 15 '18 at 16:33
  • 1
    @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. – JeremyP Jan 15 '18 at 16:38
  • if the parent process exits, parent of the children will become init, so they will not become zombies. – petertc Feb 14 '19 at 02:56