从php在后台运行unix进程 [英] Running unix process in background from php
问题描述
如果我直接在 shell 中运行这个 unix 命令:
If I run this unix command directly in shell:
$ sleep 100 &
sleep 按预期在后台运行,我可以继续在命令行中工作.
sleep runs in the background as expected, and I can continue working in the command line.
但是用 shell_exec() 和 php 尝试同样的事情我得到了不同的结果.
but trying the same thing with shell_exec() and php I get different results.
<?php
$sleep = $argv[1];
$shell="sleep " . $sleep . " &";
shell_exec($shell);
?>
在执行 php sleep.php 100
时,命令行挂起并且在 sleep 完成之前不会接受更多命令.我不确定这是否是我在 php 的 shell_exec()
/$argv
或 unix shell 中遗漏的细微差别.
when executing php sleep.php 100
the command line hangs and wont accept any more commands until sleep finishes. I am not sure whether this is a nuance I am missing with shell_exec()
/ $argv
of php or with the unix shell.
谢谢.
推荐答案
shell_exec
函数正在尝试捕获命令的输出,但在继续处理的同时无法做到这一点.事实上,如果你查看 php 源代码,php shell_exec
函数做了一个 popen
C 调用,它在命令.wait
保证子进程在子进程退出之前不会返回.
The shell_exec
function is trying to capture the output of the command, which it can't do while simultaneously continuing processing. In fact, if you look at the php source code, the php shell_exec
function does a popen
C call, which does a wait
syscall on the command. wait
guarantees that the subprocess doesn't return until the child has exited.
这篇关于从php在后台运行unix进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!