【问题标题】:using php shell_exec to execute a binary file to capture output files使用 php shell_exec 执行二进制文件来捕获输出文件
【发布时间】:2016-11-13 18:39:36
【问题描述】:

我正在使用 PHP 的 shell_exec 函数来执行 C 程序的二进制 .exe 文件。

我的 C 程序接受一个输入文本文件,并在输出中创建几个文本文件。为了将它与 Web 前端集成,我使用 php 的 shell_exec 函数来执行一个 shell 脚本,该脚本又调用二进制 C .exe 文件。

这个二进制 .exe 文件、输入文本文件、shell 脚本和 php 文件在服务器端。出于测试目的,我已授予 chmod 777 对服务器端上述文件的访问权限。

php执行shell脚本的摘录如下:

echo shell_exec('sh segments.sh 2>&1');

现在,我在这里执行一个shell脚本,shell脚本运行二进制.exe文件如下:

->segments.sh

./auto_import.exe input_file.txt -terms

auto_import 是 C 二进制 .exe 文件。

当我在终端中单独运行 shell 脚本时,它会给出正确的输出。也就是说输出将是 4-5 个不同的文本文件。

但是当我用 PHP 调用 shell 脚本时,我无法获得任何输出,并且我不确定如何从我的二进制文件接收输出,即文本文件的数量。

我尝试为我的文件提供绝对路径,例如:

在被调用的php文件shell脚本中:

echo shell_exec('sh /path/segments.sh 2>&1');

在shell脚本中,二进制文件调用如下

echo shell_exec('sh /path/binary 2>&1');

我也使用了exec函数如下:

$cmd = "/auto_import.exe input_file.txt -terms"; echo exec($cmd,$output);

在这方面你能帮帮我吗?

【问题讨论】:

    标签: php exec shell-exec


    【解决方案1】:

    如果我对您的理解正确,您的命令正在按原样执行并生成文件,您现在只需使用 PHP 阅读这些文件。一种方法如下:

    <?php
    $fileName = 'somefilethatyougenerated.txt';
    $file = fopen($fileName, "r") or die("Unable to open file!");
    $content = fread($file,filesize($fileName)); 
    // manipulate contents here
    fclose($myfile);
    ?>
    

    如果需要逐行读取文件,可以考虑使用“fgets”,如下图:How to read a file line by line in php

    【讨论】:

    • Vivek 你的问题需要澄清,现在有点模棱两可。如果 shell_exec 实际上没有运行您的文件,则通常是路径问题。确保在指定 shell_exec 时使用要执行的文件的 absolute 路径,例如 shell_exec("/usr/home/gary/php/binary.exe")而不仅仅是 shell_exec("binary.exe")。
    • 我也使用了绝对路径。但它没有用。
    • 尝试使用“system”命令在 PHP 中运行不同的 shell 脚本。例如,制作一个包含“echo 'test'”(或类似的东西)的 test.csh,并使用“system”命令测试它是否给出任何输出: $testOutput = system('test.csh', $retval) ;查看 $retval 是否包含输出。 LIkewise 修改您的脚本以提供一个输出,您可以以同样的方式再次使用 system 进行测试。
    猜你喜欢
    • 2020-01-15
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2016-02-07
    • 2011-04-14
    相关资源
    最近更新 更多