title: How to kill a process tree programmatically on Linux using C
body: <p>I am trying to write a function that spawns a child process, lets it run for a certain amount of time and then kills it if it hasn't finished:</p>
  
  <pre class="lang-c prettyprint-override"><code>int sysExecTimeout(const char * exePath, int timeoutSec);
  </code></pre>
  
  <p>In the function, I use <code>fork</code> and <code>execl</code> to spawn the child, and, when it times out, I use <code>kill(pid, SIGTERM)</code> and <code>kill(pid, SIGKILL)</code> after 2 seconds, to ensure the child dies:</p>
  
  <pre class="lang-c prettyprint-override"><code>pid_t pid = fork();
  
  if(pid == 0) {
      execl("/bin/sh", "sh", "-c", exePath);
      exit(127);
  } else if(pid != -1) {
      // timeout code
      if(timeout) {
          kill(pid, SIGTERM);
          sleep(2);
          kill(pid, SIGKILL);
      }
  }
  </code></pre>
  
  <p>I am using Linux, and it seems that when a parent process dies, the child is not killed automatically. So the two <code>kill</code> calls will just kill the <code>/bin/sh</code> process and leave the <code>exePath</code> command running, since it is  a child process of <code>/bin/sh</code>.</p>
  
  <p>I am trying to write the <code>sysExecTimeout</code> function such that it kills the entire process tree rooted at <code>pid</code>, where <code>pid</code> is the PID from <code>pid = fork()</code></p>
  
  <p>I need this because the <code>exePath</code> command will spawn other commands, which can also spawn other commands, which could get stuck and consume resources.</p>
  
  <p>I do not have control over the <code>exePath</code> binaries/scripts that get executed, so I cannot write my own parent-dies-so-kill-the-children logic in them.</p>
  
  <p>I tried using <code>kill(0, SIGTERM)</code>, which almost did the job, except it also killed my own process :)</p>
  
  <p>I am wondering if there is a flag I can turn on programatically in C that says "hey man, when I die, take all my children and kill them, and repeat recursively for their children" such that the entire process tree started from that program dies (assuming the PID/PPID chain can be followed).</p>
  
  <p>I could use that flag here:</p>
  
  <pre class="lang-c prettyprint-override"><code>if(pid == 0) {
      turnOnRecursiveDeathFlag();
  
      system(exePath);
      //execl("/bin/sh", "sh", "-c", exePath);
      exit(127);
  }
  </code></pre>
  
  <p>Is there a way to do that? I've been searching for a while, but all I can find are hacks using <code>ps -ef</code>, or modifying the children processes that you are running etc.</p>