我正在使用proc_open()
创建后台进程,想知道如何在后台进程仍在运行时从不同的文件或操作取消或停止此后台进程?
这是我的代码:
$errorLog = './error.log';
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", $errorLog, "a") // stderr is a file to write to
);
proc_open("/var/bin/php /home/hello/myscript.php &", $descriptorspec, $pipes);
我已经读过proc_terminate($process)
但似乎需要proc_open()
返回才能停止该过程。有没有办法在不proc_open()
同一脚本的情况下停止它?
执行此操作的典型方法是让子脚本获取其进程 ID(在 PHP 中带有 getmypid()
)并写出包含此 pid 的文件(通常类似于 myscript.pid
)。
然后,想要终止该脚本的任何其他内容都会检查 pid 文件是否存在,读取它(并且可能为了健壮性,检查以查看该 pid 上的目标进程是什么),然后终止目标进程。在PHP中,你可以用posix_kill()
来做到这一点。(通常,你会发送SIGTERM
或SIGKILL
,但SIGHUP
、SIGINT
,甚至SIGUSR1
或SIGUSR2
都是合适的,这取决于你希望子进程在发出信号时做什么。
或者,父进程可以使用proc_get_status()
获取子进程的 pid,并将 pid 写入某个位置供以后使用。(如果需要运行子项的多个实例和/或无法以这种方式修改子项,这可能更合适。
另外,需要注意的重要一点是,在调用 proc_open
时,您尝试要求 shell 在后台跨越进程。这是完全没有必要的。 proc_open
自己这样做,通过强制 shell 成为中介,你实际上连接到 shell,而不是你试图启动的进程。(这意味着当你的脚本存在时,这也会导致 shell 杀死孩子,而不是孩子继续在后台运行。