我使用以下代码使用proc_open打开一个进程,并将句柄和管道保存到一个文件中:
$command = "COMMAND_TO_EXECUTE";
$descriptors = 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", "error-output.txt", "a") // stderr is a file to write to
);
$pipes = array();
$processHandle = proc_open($command, $descriptors, $pipes);
if (is_resource($processHandle)) {
$processToSave = array(
"process" => $processHandle,
"pipes" => $pipes
);
file_put_contents("myfile.bin", serialize($processToSave) );
}
在第二时刻,我需要从文件中检索这个文件句柄,我已经使用了这个代码:
$processArray = unserialize(file_get_contents("myfile.bin"));
$processHandle = $processArray["process"];
$pipes = $processArray["pipes"];
但是当我从文件中检索后打印$processHandle和$pipes的var_dump时,我会得到整数而不是资源或进程,但为什么呢?
var_dump($processHandle) -> int(0)
var_dump($pipes) - > array(2) { int(0), int(0) }
当然,在这一点上,如果我试图关闭管道,我将得到一个错误,资源预期,整数给定。
我怎样才能使它工作?(注:这是我正在寻找的解决方案)
但是,我也可以获得进程的pid,然后使用这个pid来停止或杀死进程或对进程做任何其他事情,但是管道呢?我如何读/写或保存错误从/到进程?
谢谢
找到了自己的解决方案,不可能序列化资源,当脚本完成时,这些资源处理程序是空闲的。
解决方案是创建一个监听端口的守护进程,根据请求启动和停止进程。因为进程总是在运行,所以它可以维护一个处理程序进程列表,并在被请求时停止。