I'm trying to invoke a long-running shell command inside a PHP CLI script with exec()
. 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 exec()
, my signal handler is ignored. The following code works as I would expect; if I send SIGTERM to the process, it echoes SIGTERM
and exits 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 replace sleep(60);
with exec('sleep 60');
, I don't reach my signal handler until the sleep finishes. I have two questions:
- How can I get signals to work with
exec
(orshell_exec
orproc_open
)? - Upon trapping a signal, how can I kill any child processes spawned by
exec
?