运行shell_exec Laravel后API无法返回响应

时间:2018-11-22 08:23:48

标签: php laravel shell api exec

当用户调用我的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秒,因此我将 max_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);
    }
});

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

1 个答案:

答案 0 :(得分:-1)

已解决!

在我的 shell.sh 中包括使nginx重新启动的行。编辑我的sh文件即可解决问题。