Linux 使用php在后台执行shell脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7657846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:31:13  来源:igfitidea点击:

Executing a shell script in background with php

phplinuxshell

提问by Jed

I need to execute a shell script. The catch is I want to do this

我需要执行一个shell脚本。问题是我想做这个

$Command = "nohup cvlc input --sout '#transcode {vcodec=h264,acodec=mp3,samplerate=44100}:std{access=http,mux=ffmpeg{mux=flv},dst=0.0.0.0:8083/".output"}' &";
$str = shell_exec($Command);

I dont want it to wait till the command is finished, i want it to run in a background process. I do not want another php thread as it will timeout the command can take up to 3 hours to finish.

我不希望它等到命令完成,我希望它在后台进程中运行。我不想要另一个 php 线程,因为它会超时命令最多需要 3 小时才能完成。

采纳答案by Matthieu Napoli

$str = shell_exec($Command.' 2>&1 > out.log');

You need to redirect the output of the command.

您需要重定向命令的输出。

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

如果一个程序是用这个函数启动的,为了让它在后台继续运行,程序的输出必须重定向到一个文件或另一个输出流。如果不这样做,将导致 PHP 挂起,直到程序执行结束。

http://php.net/manual/en/function.exec.php

http://php.net/manual/en/function.exec.php

回答by Eduardo Russo

You can try running your command in background using a function like this one:

您可以尝试使用如下函数在后台运行您的命令:

function exec_bg($cmd) { 
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    } 
    else { 
        exec($cmd . " > /dev/null &");   
    }
}

This makes your shell command runs, but the php flow continues.

这将使您的 shell 命令运行,但 php 流程仍在继续。