停止 Symfony 控制台命令

Stop a Symfony Console command

我有一个连续循环的 Symfony 控制台命令

protected function execute(InputInterface $input, OutputInterface $output)
{
   //... 

   pcntl_signal(SIGHUP, [$this, 'stopCommand']);

    $this->shouldStop = false;

    while (true) {


        pcntl_signal_dispatch();

        if ($this->shouldStop) {
            break;
        }
        sleep(60);
    }
}

protected function stopCommand()
{
    $this->shouldStop = true;
}

我希望我能用控制器阻止他

    public function stopAction()
{ 
    posix_kill(posix_getpid(), SIGHUP);

    return new Response('ok');
}

但是不知道为什么不行

它可能不起作用,因为控制台命令 运行 在与控制器操作不同的进程中。尝试在执行开始时将控制台命令的 PID 号存储到文件中,例如:

file_put_contents("/tmp/console_command.pid", posix_getpid());

然后在控制器中使用此代码:

posix_kill(file_get_contents("/tmp/console_command.pid"), SIGHUP);