【问题标题】:API can't return respone after run shell_exec Laravel运行 shell_exec Laravel 后 API 无法返回响应
【发布时间】:2019-04-24 21:09:35
【问题描述】:

当用户调用我的 API 时,我正在尝试执行一个 shell 文件。这是我在 Laravel routes/api.php 中编写的代码:

    Route::get('process', function() {
         define("SHELL_PATH","/home/ubuntu");
         ini_set('max_execution_time', 60);

         $arrProcess = array(
             "sudo sh",
             "./shell.sh",
             "NAME=taanh",
             "2>&1"
         );

         chdir(SHELL_PATH);
         $process = shell_exec(implode(" ", $arrProcess));
         return response()->json([
             "status" => 0,
             "process" => $process
         ],200);
    });

我的 shell.sh 执行大约需要 30 秒,因此我将 ma​​x_execution_time 设置为 60。我尝试将其设置为 300

shell 运行成功但 api 返回 连接已重置 而不是我的 json 响应。

我也尝试过 Symfony/Process,但仍然遇到这个问题。

define("SHELL_PATH","/home/ubuntu");
ini_set('max_execution_time', 60);

$arrProcess = array(
    "sudo sh",
    "./shell.sh",
    "NAME=taanh",
    "2>&1"
);

chdir(SHELL_PATH);
$process = new Process(implode(" ", $arrProcess));
$process->run(function ($type, $buffer) {
    if (Process::ERR === $type) {
        return response()->json([
            "status" => 1,
            "code" => 5004,
            "msg" => "Error when run site",
        ],500);
    } else {
        return response()->json([
            "status" => 0,
            "msg" => "Run shell successfully",
            "process" => $buffer
        ],200);
    }
});

我的代码有问题吗?谢谢!

【问题讨论】:

    标签: php laravel shell api exec


    【解决方案1】:

    解决了!

    在我的 shell.sh 中包含一行让 nginx 重新启动。编辑我的 sh 文件修复问题。

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2017-08-31
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多