我正在尝试使用popen在后台运行php脚本。但是,我需要传递一个(相当大的)序列化对象。
$cmd = "php background_test.php >log/output.log &";
$fh = popen($cmd, 'w');
fwrite($fh, $data);
fclose($fh);
//pclose($fh);
如果没有&符号,此代码执行正常,但父脚本将等待子代完成运行。使用&符号STDIN没有数据。
有什么想法吗?
答案 0 :(得分:1)
你可以尝试让子进程写入数据,主脚本继续正常。
像这样的东西
// Fork a child process
$pid = pcntl_fork();
// Unable to fork
if ($pid == -1) {
die('error');
}
// We are the parent
elseif ($pid) {
// do nothing
}
// We are the child
else {
$cmd = "php background_test.php >log/output.log";
$fh = popen($cmd, 'w');
fwrite($fh, $data);
fclose($fh);
exit();
}
// parent will continue here
// child will exit above
在此处详细了解:https://sites.google.com/a/van-steenbeek.net/archive/php_pcntl_fork
在php文档中检查函数pcntl_waitpid()(zombies就不见了)。
答案 1 :(得分:0)
据我所知,php无法在后台发送进程并继续提供其STDIN(但也许我错了)。你还有两个选择:
background_test.php
以从命令行获取输入并转换php background_test.php arg1 arg2 ... >log/output.log &
中的命令行background_test.php
脚本,如下面的代码所示第2点的例子:
<?
$tmp_file = tempnam();
file_put_content($tmp_file, $data);
$cmd = "php background_test.php < $tmp_name > log/output.log &";
exec($cmd);
答案 2 :(得分:0)
让后台进程侦听套接字文件。然后从PHP打开套接字文件并在那里发送您的序列化数据。当您的后台守护进程通过套接字接收连接时,将其设置为fork,然后读取数据然后进行处理。
你需要做一些阅读,但我认为这是实现这一目标的最佳方式。通过套接字我的意思是unix套接字文件,但你也可以通过网络使用它。
http://gearman.org/也是@Joshua
提到的一个很好的选择