7

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

$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.

Matthieu Napoli
  • 45,472
  • 43
  • 162
  • 249
Jed
  • 869
  • 2
  • 14
  • 31

2 Answers2

10

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.

BenMorel
  • 31,815
  • 47
  • 169
  • 296
Eduardo Russo
  • 3,843
  • 2
  • 20
  • 36
10
$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.

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

Matthieu Napoli
  • 45,472
  • 43
  • 162
  • 249