Skip to content

Instantly share code, notes, and snippets.

@darkterminal
Forked from mul14/command.php
Created April 7, 2024 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkterminal/6c2c0ce32836dc719462c113ff8068fe to your computer and use it in GitHub Desktop.
Save darkterminal/6c2c0ce32836dc719462c113ff8068fe to your computer and use it in GitHub Desktop.
Send signal to a process with PHP https://youtu.be/H2lp_jcfmu0
#!/usr/bin/env php
<?php
define('PID_PATH', '/tmp/myapp.pid');
define ('PID', (int) file_get_contents(PID_PATH));
if (empty($argv[1])) {
echo <<<INFO
Usage:
${$argv[0]} [status|restart|stop]
INFO;
exit;
}
$command = $argv[1];
if ($command === 'status') {
posix_kill(PID, SIGUSR1);
}
if ($command === 'restart') {
posix_kill(PID, SIGCONT);
}
if ($command === 'stop') {
posix_kill(PID, SIGTERM);
}
#!/usr/bin/env php
<?php
declare(ticks = 1);
define('PID_PATH', '/tmp/myapp.pid');
register_shutdown_function(function () {
// Will run when shutdown.
echo 'Deleting temporary file...' . PHP_EOL;
unlink(PID_PATH);
echo 'Done.' . PHP_EOL;
});
pcntl_signal(SIGUSR1, function () {
// Do something when catch "info" signal.
echo 'Show information about this process.' . PHP_EOL;
});
pcntl_signal(SIGCONT, function () {
// Do something when catch "continue/restart" signal.
echo 'Restart...'. PHP_EOL;
});
pcntl_signal(SIGTERM, function () {
// Do something when catch "terminate" signal.
die('Catch terminate signal. Exiting process...' . PHP_EOL);
});
echo 'Run with PID ' . posix_getpid() . PHP_EOL;
$fp = fopen(PID_PATH, 'w');
fwrite($fp, posix_getpid());
fclose($fp);
while (true) {
// Do something inside event-loop
sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment