07/10/2017 - PHP, SYMFONY
In example below, we are going to use pcntl_signal
function to let our command finish its job first and then exit. It is useful for preventing unexpected terminations which originate from ctrl+c
action and kill PID
command. We'll be using a symfony command as an example.
I will just print a message but you could use it for closing database connection, saving data, closing files, writing to a log file etc.
namespace AppBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HelloCommand extends Command
{
/** @var OutputInterface */
private $output;
protected function configure()
{
$this->setName('hello');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
declare(ticks = 1);
pcntl_signal(SIGINT, [$this, 'doInterrupt']);
pcntl_signal(SIGTERM, [$this, 'doTerminate']);
while (true) {
$output->writeln('Hello '.date('s'));
sleep(1);
}
}
/**
* Ctrl-C
*/
private function doInterrupt()
{
$this->output->writeln('Interruption signal received.');
exit;
}
/**
* kill PID
*/
private function doTerminate()
{
$this->output->writeln('Termination signal received.');
exit;
}
}
$ bin/console hello
Hello 36
Hello 37
Hello 38
Hello 39
Termination signal received.
$ bin/console hello
Hello 17
Hello 18
Hello 19
^C
Interruption signal received.