title: How to interrupt exec and kill child processes
body: <p>I'm trying to invoke a long-running shell command inside a PHP CLI script with <code>exec()</code>. But I can't for the life of me figure out how to interrupt the PHP script and kill the spawned child process(s). It seems like as soon as I call <code>exec()</code>, my signal handler is ignored. The following code works as I would expect; if I send SIGTERM to the process, it echoes <code>SIGTERM</code> and exits immediately.</p>
  
  <pre><code>&lt;?php
    declare(ticks = 1);
  
    function sig_handler($signo) {
      switch ($signo) {
        case SIGTERM:
          echo 'SIGTERM' . PHP_EOL;
          flush();
          break;
        default:
      }
    }
  
    pcntl_signal(SIGTERM, 'sig_handler', false);
  
    sleep(60);
  ?&gt;
  </code></pre>
  
  <p>However, if I replace <code>sleep(60);</code> with <code>exec('sleep 60');</code>, I don't reach my signal handler until the sleep finishes. I have two questions:</p>
  
  <ol>
  <li>How can I get signals to work with <code>exec</code> (or <code>shell_exec</code> or <code>proc_open</code>)?</li>
  <li>Upon trapping a signal, how can I kill any child processes spawned by <code>exec</code>?</li>
  </ol>