使用 proc_open() 进行多输入 [英] Multiple input with proc_open()
问题描述
我目前正在开发一个在线程序.我正在编写一个 php 脚本,它在命令行中使用 proc_open() (在 Linux Ubuntu 下)执行命令.到目前为止,这是我的代码:
I'm currently working on an online program. I'm writing a php script that executes a command in the command line with proc_open() (under Linux Ubuntu). This is my code so far:
<?php
$cmd = "./power";
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w"),
);
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], "4");
fwrite($pipes[0], "5");
fclose($pipes[0]);
while($pdf_content = fgets($pipes[1]))
{
echo $pdf_content . "<br>";
}
fclose($pipes[1]);
$return_value = proc_close($process);
}
?>
power 是一个要求输入 2 次的程序(它需要一个底数和一个指数并计算底数 ^ 指数).它是用汇编写的.但是当我运行这个脚本时,我得到了错误的输出.我的输出是1",但我希望输出 4^5.
power is a program that asks for input 2 times (it takes a base and an exponent and calculates base ^ exponent). It's written in Assembly. But when I run this script, I get wrong output. My output is "1" but I expect 4^5 as output.
当我运行一个接受一个输入的程序时,它可以工作(我测试了一个简单的程序,该程序将输入的值增加一).
When I Run a program that takes one input, it works (I've tested an easy program that increments the entered value by one).
我想我遗漏了一些关于 fwrite 命令的内容.有人可以帮我吗?
I think I'm missing something regarding the fwrite command. Could anyone please help me?
提前致谢!
推荐答案
你忘记给管道写一个换行符,所以你的程序会认为它只有 45
作为输入.试试这个:
You forgot to write a newline to the pipe, so your program will think that it got only 45
as input. Try this:
fwrite($pipes[0], "4");
fwrite($pipes[0], "\n");
fwrite($pipes[0], "5");
fclose($pipes[0]);
或更短:
fwrite($pipes[0], "4\n5");
fclose($pipes[0]);
这篇关于使用 proc_open() 进行多输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!