[英]PHP execute process in background and get results
I'm looking for an easy way to start a process (through php) in the background (I don't want my php script to wait for the end). 我正在寻找一种在后台启动过程(通过php)的简单方法(我不希望我的php脚本等待结束)。 Although I would need to also have a handle on the process in other to catch the end of its execution to do some afterwork.
尽管我还需要处理其他流程,才能赶上执行结束才能做一些后续工作。
So far I manager to start the process with something like 到目前为止,我已经开始以类似
pclose ( popen ( "\"start /B " . $commands . " > log.txt\"", "r" ) );
But I'm not sure on how to find if the process is terminated (and maybe it's too early in the morning but I can't find much about it using popen and start /B) 但是我不确定如何确定该过程是否终止(也许还为时过早,但是我无法使用popen并启动/ B来找到更多有关该过程的信息)
I'm using the "start" way because ideally the solution should run on both windows and linux. 我使用“开始”方式,因为理想情况下该解决方案应同时在Windows和Linux上运行。
Any input would be appreciated. 任何输入将不胜感激。 Thanks for the help!
谢谢您的帮助!
I had to perform a similar task, and although I had a slightly different approach, is quite similar to what you are trying to do, and I went through sockets: 我不得不执行类似的任务,尽管我使用的方法略有不同,但与您尝试执行的操作非常相似,并且我经历了套接字:
1st step: get the process PID and call socket file 第一步:获取进程PID并调用套接字文件
//windows
$desc = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
);
$p = proc_open($command, $desc, $pipes);
$status = proc_get_status($p);
$ppid = $status["pid"];
$output = array_filter(explode(" ", shell_exec("wmic process get parentprocessid,processid | find \"$ppid\"")));
array_pop($output);
$pid = end($output);
//unix
$pid = trim(shell_exec(sprintf('%s > %s 2>&1 & echo $!', $command, $outputFile)))
//Call the daemon with the socket stuff and pass the pid
shell_exec("path/to/daemon.php $pid");
2nd step: the daemon file 第二步:守护程序文件
The daemon.php should open a Socket that checks in intervals if the process with given pid is still running, and if not, send a message and exit the process. daemon.php应该打开一个套接字,该套接字定期检查具有给定pid的进程是否仍在运行,如果没有运行,则发送一条消息并退出该进程。 I didn´t post the socket stuff because I think there are good libraries for that, and my approach was hand-made what can make it difficult to understand.
我没有发布套接字的东西,因为我认为有很好的库,而我的方法是手工制作的,这会使它很难理解。
3rd: process socket messages where needed 第三:在需要的地方处理套接字消息
Probably you want to do that in javascript 可能您想用javascript做到这一点
<script language="javascript" type="text/javascript">
$(document).ready(function(){
var wsUri = "ws://host:port/daemon.php";
websocket = new WebSocket(wsUri);
websocket.onopen = function(ev) {
}
websocket.onmessage = function(ev) {
var msg = JSON.parse(ev.data);
switch( msg.action){
case "process_finisihed":{
//doThingsHere
}
break;
}
};
websocket.onerror = function(ev){ console.debug(ev); };
websocket.onclose = function(ev){};
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.