Ara*_*ian 8 php fork subprocess kill-process pcntl
Lemme首先给出了我所拥有的代码的基本描述.我从一个主要的父进程开始(注意:为了简单起见,我没有显示所有函数.如果你需要我在任何时候进行扩展,请告诉我):
declare(ticks=1);
pcntl_signal(SIGHUP, array('forker', 'restartSignalHandler'));
if(forker_is_not_running()){
new Forker();
}
class Forker {
private $active_forks = array();
private $parent_pid = null;
public function __construct(){
$this->parent_pid = getmypid();
$this->create_fork();
$this->wait_for_active();
}
public function wait_for_active(){
while(!empty($this->active_forks)){
foreach($this->active_forks as $k=>$fork){
if($this->fork_no_longer_running($fork)){
unset($this->active_forks[$k]);
}
}
}
}
// Pseudo code
public function fork_no_longer_running($pid){
// return true if 'ps -elf | grep $pid' doesn't returns only the grep command
// else return false (aka the fork is still running)
}
public function create_fork(){
$pid = pcntl_fork();
if($pid == -1){
posix_kill($this->parent_pid, SIGTERM);
} else if($pid){
// add the pid to the current fork
$this->active_forks[] = $pid;
} else {
// Run our process
pcntl_exec('/usr/bin/php', array('/domain/dev/www/index.php','holder','process'));
exit(0);
}
}
public function restartSignalHandler(){
$forks = $this->active_forks;
foreach($forks as $pid){
$this->create_fork();
posix_kill($pid, SIGINT);
}
}
}
class holder {
public function process(){
$x = new Processor();
}
}
class Processor {
public function __construct(){
pcntl_signal(SIGINT, array($this, "shutdownSignalHandler"));
}
public function shutdownSignalHandler(){
echo "Shutting down";
exit;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是发生的事情:
Lemme知道是否需要更多细节/没有意义.我无法弄清楚为什么第一次它会正确地杀死孩子,但第二次它没有.
甚至WEIRDER部分是当我更改它以便我更改我的重启处理程序以便它继续尝试使用SIGINT杀死子项时,它每次都失败,但是当我发送一个SIGKILL命令它会杀死子进程:
if($time_passed > 60){
posix_kill($pid, SIGKILL);
}
Run Code Online (Sandbox Code Playgroud)
我需要孩子能够被SIGINT杀死才能正确处理它.我不想只是SIGKILL它.是否有任何理由为什么第二次围绕SIGINT不起作用,但SIGKILL会?
小智 1
首先,你不需要分叉。您的代码在子进程中执行 exec,您基本上可以在不分叉的情况下运行 exec,并且操作系统将生成您的命令作为子进程。如果你想使用fork,只需将include文件放在子进程中而不是执行。
public function create_fork(){
//no need to actually fork!
pcntl_exec('/usr/bin/php', array('/domain/dev/www/index.php','holder','process'));
}
//if you want to fork, better do it like this :
public function create_fork(){
$pid = pcntl_fork();
if($pid == -1){
posix_kill($this->parent_pid, SIGTERM);
} else if($pid){
// add the pid to the current fork
$this->active_forks[] = $pid;
} else {
// Run our process
include '/domain/dev/www/index.php';
SomeClass::someMethod();
exit(0);
}
}
Run Code Online (Sandbox Code Playgroud)
另外,使用叉子时,需要waitpid为孩子们使用。因此,在您的代码中您需要插入类似以下内容:
//somewhere in a loop :
$pidOfExittedChild = pcntl_waitpid (-1, $status, WNOHANG);
if ($pidOfExittedChild) {
//a child has exitted, check its $status and do something
}
Run Code Online (Sandbox Code Playgroud)
查看更多信息: http ://php.net/manual/en/function.pcntl-waitpid.php