Last active
November 20, 2019 12:16
-
-
Save mlasker/4b28b374dda62c46975abdd437fdee13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This is small demonstration of PHPs signal handling behavior. | |
* | |
* Both methods will fork children using pcntl_fork and output whether or not forked parent/child were created inside | |
* of the registered sigHandler function, if it's the child or parent, and their respective PIDs. | |
* | |
* If you run spawnChildInsideHandler and attempt to send a SIGTERM (15) to either of the two processes | |
* you will receive no response. To exit you will have to force kill with SIGKILL (9) | |
* | |
* If you run spawnChildOutsideHandler and attempt to send a SIGTERM (15) to either of the two processes you should see | |
* output from the sigHandler function. | |
* | |
* The question to be answered is if this is intended behavior that isn't documented or a bug. | |
*/ | |
spawnChildInsideHandler(); | |
//spawnChildOutsideOfHandler(); | |
function spawnChildOutsideOfHandler() { | |
pcntl_async_signals(true); | |
pcntl_signal(SIGTERM, "sigHandler", false); | |
$pid = pcntl_fork(); | |
// child process | |
if ($pid === 0) { | |
echo "[Forked Without Signal] [CHILD] PID = " . getmypid() . PHP_EOL; | |
wait(); | |
} // parent process | |
elseif ($pid) { | |
echo "[Forked Without Signal] [PARENT] PID = " . getmypid() . PHP_EOL; | |
wait(); | |
} | |
} | |
function spawnChildInsideHandler() { | |
pcntl_async_signals(true); | |
pcntl_signal(SIGTERM, "sigHandler", false); | |
pcntl_signal(SIGHUP, "sigHandler", false); | |
posix_kill(getmypid(), SIGHUP); | |
} | |
function sigHandler($sigNum) | |
{ | |
$mypid = getmypid(); | |
if ($sigNum === SIGHUP) { | |
echo "[{$mypid}] Received SIGHUP, forking off children\n"; | |
$pid = pcntl_fork(); | |
// child process | |
if ($pid === 0) { | |
echo "[Forked inside handler] [CHILD] PID = " . getmypid() . PHP_EOL; | |
wait(); | |
} // parent process | |
elseif ($pid) { | |
echo "[Forked inside handler] [PARENT] PID = " . getmypid() . PHP_EOL; | |
wait(); | |
} | |
} | |
echo "[{$mypid}] Received signal {$sigNum}\n"; | |
} | |
function wait() { | |
while (true) { | |
sleep(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment