从php system()函数获取完整输出

时间:2011-12-02 06:38:48

标签: php c++ cmd

我的php system()函数输出有问题。所以这里是代码:

system("c:\\Dev-Cpp\\bin\\g++.exe c:\\wamp\\www\\hello.cpp -O3 -o c:\\wamp\\www\\hello.exe", $output);

echo $output;

所以如果我的hello.cpp确实编译我得到0,如果不是,我得到1。

如果我从CMD运行相同的东西,而不是只给1,那么就会给我一个完整的错误。

如何使用php system()函数获取完整错误?

1 个答案:

答案 0 :(得分:2)

您只捕获程序的返回代码,该代码通常是一个整数,其中0表示“成功”,其他任何内容都是错误代码。

如果你想捕捉程序的实际输出(即STDOUT and/or STDERR)你需要做以下事情之一:

  • 使用输出缓冲来捕获system()
  • 的输出
$command = "c:\\Dev-Cpp\\bin\\g++.exe c:\\wamp\\www\\hello.cpp -O3 -o c:\\wamp\\www\\hello.exe";
ob_start();
system($command, $returnCode);
$output = ob_get_clean();
exec($command, $output, $returnCode);
// ...or...
$output = shell_exec($command);
// ...or...
$output = `$command`;

如果你想捕获STDERR的输出(我怀疑你这样做),你可能需要在命令字符串的末尾添加2>&1

或者,您可能需要查看proc_open(),这更复杂,但可以让您对子进程及其执行/传递数据的方式进行更精细的控制。

相关问题