You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用exec()调用.exe无输出,返回值-1073740791求助

解决PHP exec()调用exe返回-1073740791且无输出的问题

首先,先明确你遇到的返回码 -1073740791 对应的是Windows系统错误码 0xC0000409,这个错误通常和命令行参数解析失败或者程序运行时栈缓冲区溢出有关,结合你的代码来看,参数拼接的方式大概率是核心问题,下面一步步帮你排查解决:

1. 修复命令行参数的拼接方式

你现在手动给$_GET["query"]加引号的方式很脆弱,如果参数里包含双引号、空格或者特殊字符(比如&、|),会直接破坏命令的结构,导致exe无法正确解析参数。正确的做法是用PHP的escapeshellarg()函数来转义每个参数,它会自动处理特殊字符并添加正确的引号:

<?php
if (isset($_GET["query"]) && isset($_GET["number"])) {
    $file = 'src\\infix_to_postfix_and_evaluate.exe';
    // 用escapeshellarg转义每个参数,避免解析错误
    $arg1 = escapeshellarg($_GET["number"]);
    $arg2 = escapeshellarg($_GET["query"]);
    
    if (file_exists($file)) {
        echo "<p>file " . htmlspecialchars($file) . " exists</p>";
    } else {
        echo "<p>file " . htmlspecialchars($file) . " does not exist</p>";
    }
    
    // 拼接安全的命令
    $command = $file . ' ' . $arg1 . ' ' . $arg2;
    // 可选:打印命令到页面,方便手动测试
    echo "<p>Executing command: " . htmlspecialchars($command) . "</p>";
    
    exec($command, $lines, $return);
    
    // 输出调试信息
    echo "<p>Return code: " . $return . "</p>";
    echo "<p>Output lines:</p>";
    echo "<pre>" . print_r($lines, true) . "</pre>";
}
?>

2. 捕获程序的错误输出

exec()默认只捕获标准输出(stdout),如果你的exe程序在运行时产生了错误输出(stderr),你是看不到的。可以通过在命令末尾添加2>&1把stderr重定向到stdout,这样就能看到所有输出:

$command = $file . ' ' . $arg1 . ' ' . $arg2 . ' 2>&1';
exec($command, $lines, $return);

3. 检查程序运行环境和权限

  • 工作目录问题:你的exe可能需要在特定目录下运行(比如依赖同目录下的配置文件或动态库),可以先切换到exe所在的目录再执行:
    chdir('src');
    $file = 'infix_to_postfix_and_evaluate.exe';
    // 后续执行命令...
    
  • 权限问题:确保PHP运行的用户(比如IIS的IIS_IUSRS账号、Apache的www-data账号)有读取和执行该exe文件的权限,同时exe依赖的动态库(比如VC++ Redistributable)已经安装在服务器上。
  • 手动测试命令:把代码里打印出来的$command复制到服务器的命令提示符(CMD)里手动运行,看看是否能正常输出。如果手动运行也有问题,那问题出在exe程序本身,需要排查exe的逻辑。

4. 尝试用proc_open()替代exec()

如果exec()还是无法获取输出,可以用proc_open(),它能更精细地控制进程的输入输出,适合调试复杂的外部程序调用:

$descriptorspec = array(
    0 => array("pipe", "r"),  // 标准输入
    1 => array("pipe", "w"),  // 标准输出
    2 => array("pipe", "w")   // 标准错误
);

$process = proc_open($command, $descriptorspec, $pipes);

if (is_resource($process)) {
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $return = proc_close($process);
    
    echo "<p>Return code: " . $return . "</p>";
    echo "<p>Stdout:</p><pre>" . htmlspecialchars($stdout) . "</pre>";
    echo "<p>Stderr:</p><pre>" . htmlspecialchars($stderr) . "</pre>";
}

通过上面的步骤,你应该能定位到问题所在,大概率是参数拼接错误导致exe无法正确执行,或者是权限/环境问题导致程序崩溃。

内容的提问来源于stack exchange,提问作者Petr Pilař

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:14:27