我的 PHP Web 应用程序从流中接收数据。加载页面后,我需要使用or打开.exe
文件,并且在短时间内会有新数据出现,因此我必须为此键入特定命令以获取其返回值,我该怎么做?system()
exec()
.exe
我只能在命令提示符下手动执行此操作
path/to/.exe :: hit 'Enter'
command1 params1
//...
您正在寻找的是proc_open()
. http://php.net/manual/en/function.proc-open.php
这将允许您使用 STDIO 流与单独的进程进行通信。
$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", "/tmp/error-output.txt", "a") // stderr is a file to write to
);
$cwd = '/tmp';
$env = array('some_option' => 'aeiou');
$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
如果您需要多个侦听器,您也可以考虑共享内存,但这种情况听起来您会从使用队列中受益。
文档msg_get_queue
, msg_receive
,msg_send
例子
// Send
if (msg_queue_exists(12345)) {
$mqh = msg_get_queue(12345);
$result = msg_send($mqh , 1, 'data', true);
}
// Receive
$mqh = msg_get_queue(12345, 0666);
$mqst = msg_stat_queue($mqh);
while ($mqst['msg_qnum']) {
msg_receive($mqh, 0, $msgtype, 2048, $data, true);
// Spawn your process
$mqst = msg_stat_queue($mqh);
}
编辑
信号量功能在 Windows 上不可用,正如上面所建议的,您最好的选择是使用popen
(单向)或proc_open
双向支持。