How to interrupt exec and kill child processes

I am trying to call a long-running shell command inside a CLI script with exec(). But I can’t understand for the rest of my life how to interrupt a PHP script and kill the child process (s) generated. It looks like as soon as I call exec(), my signal handler is ignored. The following code works as I expected; if I send SIGTERM to the process, it will echo SIGTERMand exit immediately.

<?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);
?>

However, if I replaced sleep(60);with exec('sleep 60');, I won’t get to my signal handler until the dream ends. I have two questions:

  • How can I get signals to work with exec(or shell_execor proc_open)?
  • After capturing the signal, how can I kill any child processes spawned exec?
+3
1

:

, , . PHP .

( .) , .

, , -, fork + exec:

switch ($pid = pcntl_fork()) {
  case -1: // failed to create process
     die('Fork failed');
  case 0: // child
     pcntl_exec($path,$args);
     die('Exec failed');
}

, $pid, SIGINT posix_kill($pid, SIGINT).

: , proc_open proc_terminate.

+5
source

All Articles