【问题标题】:How to get output from executable file in php如何从php中的可执行文件中获取输出
【发布时间】:2019-11-18 08:31:09
【问题描述】:

我无法通过 php 从可执行文件 (a.out) 中获取输出。 我的 php 代码是:

$file = "/path/main.cpp";
$command="cd $path && c++ -lm ".$file;
exec($command);
$output = exec("cd $path && ./a.out");
exec("cd $path && ./a.out > res.txt");
var_dump($output);

所有命令都已执行,但我得到的是空值;

exec("cd $path && ./a.out > res.txt");

这个命令也被执行了,res.txt 是在文件夹中创建的,但是是空文件。 如何解决这个问题呢? 我的操作系统是 CentOS 7

【问题讨论】:

  • 好像你想要popen
  • 关于重定向中的“空文件”,您确定程序实际上会生成任何输出吗?还是说编译成功,a.out 程序存在?
  • 是的,我从终端检查,没问题,但是通过 php 没有输出
  • 也尝试捕获错误输出,看看它是否失败 (stackoverflow.com/questions/3863699/…)。
  • 我明白了:sh: ./a.out: Permission denied

标签: php


【解决方案1】:

为了使用 PHP 获取命令的输出,您可以使用 shell_exec 函数:

shell_exec

shell_exec — 通过 shell 执行命令并返回完整的输出 作为字符串

所以,试试这个:

$output = shell_exec("cd $path && ./a.out");

【讨论】:

  • sh: ./a.out: 权限被拒绝
  • @BakhodirIsmatov 所以问题是另一个......当你解决它时,shell_exec 会做你需要的
  • apache 可以运行 a.out 吗?
  • @BakhodirIsmatov 如果可以的话尝试从终端运行它,否则尝试在shell_exec:echo shell_exec('echo "it works";'); 中运行它。因为我不知道a.out 包含什么,所以我无法帮助您。
猜你喜欢
  • 2010-12-14
  • 1970-01-01
  • 2023-03-24
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多