ThP
ThP

Reputation: 2332

send SIGINT to child process

I am trying to create a child process and then send SIGINT to the child without terminating the parent. I tried this:

pid=fork();
  if (!pid)
  {
      setpgrp();
      cout<<"waiting...\n";
      while(1);
  }
  else
      {
      cout<<"parent";
      wait(NULL);
      }

but when I hit C-c both process were terminated

Upvotes: 2

Views: 11909

Answers (3)

paxdiablo
paxdiablo

Reputation: 881423

Don't use CTRL-C, this sends a signal to all processes with the same controlling terminal (ie, in the same session). That's something that setpgid doesn't change though I think there's a setsid (set session ID) call for that purpose.

The easiest solution is simply to target the specific process rather than a session. From the command line:

kill -INT pid

From C:

kill (pid, SIGINT);

where pid is the process ID you want to send the signal to.

The parent can get the relevant PID from the return value from fork(). If a child wants its own PID, it can call getpid().

Upvotes: 9

DigitalRoss
DigitalRoss

Reputation: 146073

Aha, the mystery of process groups and sessions and process group leaders and session group leaders appears again.

Your control/C sent the signal to a group. You need to signal an individual pid, so follow paxdiablo's instructions or signal ("kill") the child from the parent. And don't busy wait! Put a sleep(1) in the loop, or better yet, one of the wait(2) system calls.

Upvotes: 5

Matthew Iselin
Matthew Iselin

Reputation: 10670

You could try implementing a SIGINT signal handler which, if a child process is running, kills the child process (and if not, shuts down the application).

Alternatively, set the parent's SIGINT handler to SIG_IGN and the child's to SIG_DFL.

Upvotes: 3

Related Questions