Skip to content

Instantly share code, notes, and snippets.

@FerraBraiZ
Forked from pcdinh/process1.php
Last active March 23, 2024 16:10
Show Gist options
  • Save FerraBraiZ/33ccdaef7b49cf9237aaac975c2f2d9d to your computer and use it in GitHub Desktop.
Save FerraBraiZ/33ccdaef7b49cf9237aaac975c2f2d9d to your computer and use it in GitHub Desktop.
PHP Handle Signals
<?php
declare(ticks = 1);
function handleExit($signal)
{
error_log("Caught a $signal signal, a worker process exiting\n", 3, './error-child-log');
exit(1);
}
pcntl_signal(SIGTERM, 'handleExit');
pcntl_signal(SIGQUIT, 'handleExit');
pcntl_signal(SIGINT, 'handleExit');
pcntl_signal(SIGSTOP, 'handleExit');
pcntl_signal(SIGABRT, 'handleExit');
pcntl_signal(SIGHUP, 'handleExit');
$i = 0;
// Will run in 100 seconds
while ($i < 100)
{
$i++;
echo "Running \n.";
sleep(1);
}
?>
#!/usr/local/php5-fcgi/bin/php
<?php
/**
* Run it: php test3.php
*/
declare(ticks = 1);
function handleChildExit($signal)
{
echo ("Caught a SIGCHLD signal, a worker process exiting\n");
while (($pid = pcntl_waitpid(0, $status, WNOHANG)) != - 1)
{
if (0 === $pid)
{
break;
}
if (!pcntl_wifexited($status))
{
echo ("Child process $pid killed with status $status\n");
}
else
{
echo ("Child process $pid exited with status $status\n");
echo "Command used ".$status['command']."\n";
echo "Termination signal: ".$status['termsig']."\n";
echo "Is stopped: ".$status['stopped']."\n";
echo "Stop signal: ".$status['stopsig']."\n";
}
}
}
// In case worker process exits
pcntl_signal(SIGCHLD, 'handleChildExit');
function start()
{
$descriptors = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array("file", "error-output.txt", "a"));
$pipes = array();
// Tested
// $process = proc_open('exec /usr/local/php5-fcgi/bin/php process1.php', $descriptors, $pipes);
$process = proc_open('/usr/local/php5-fcgi/bin/php process1.php', $descriptors, $pipes);
$status = proc_get_status($process);
if (true === $status['running'])
{
echo "Started process Id\n";
}
else
{
echo "Unable to start a process\n";
}
$i = 0;
while ($i < 10)
{
$status = proc_get_status($process);
if (true === $status['running'])
{
echo "Process Id {$status['pid']} is running\n";
echo "Command used ".$status['command']."\n";
}
else
{
echo "Not running\n";
}
$i++;
}
return array(
'pid' => $status['pid'],
'handle' => $process
);
}
echo "Parent process ID: ".posix_getpid()."\n";
$running = array();
$rs = start();
$running[$rs['pid']] = $rs;
$i = 0;
while ($i < 1000)
{
foreach ($running as $pid => $info)
{
$status = proc_get_status($info['handle']);
if (true === $status['running'])
{
echo "Process $pid is running \n";
}
else
{
echo "Process $pid is not running \n";
}
}
sleep(1);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment