Run a piped shell command in background using PHP
I'm trying to execute a command in the background using PHP so the web application can continue to load, but having no luck so far.
The command is for a live streaming application, so involves the following:
<stream pre-process> | ffmpeg <options> | <stream segmenter>
I can stick the above in a script and execute it fine in the background in bash with &, but this doesn't work in PHP. I also tried using nohup before, and "nohup & echo $!", but no luck.
I am also piping all of stderr to /dev/null, and I can verify in apache logs that there is no output generated when I execute the command (but it is executing).
Some example code below.. what I have after this code doesn't execute until this finishes, which is a long time.
function streamVid ($mid, $width, $height, $br) {
$cdir = "./temp";
$zmstrm = "zmstreamer -m ".$mid." 2> /dev/null";
$seg = "segmenter - 3 ".$cdir."/sample_".$mid." ".$cdir."/stream_".$mid.".m3u8 ./ 2>/dev/null";
$ffparms = "-f mpegts -analyzeduration 0 -acodec copy -s ".$width."x".$height." -vcodec libx264 -b ".$br." -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -bt 200k -maxrate ".$br." -bufsize ".$br." -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -level 30 -aspect 320:240 -g 30 -analyzeduration 0 -async 2 - 2> /dev/null";
$url = $zmstrm . " | ffmpeg -t 10 -analyzeduration开发者_如何学编程 0 -i - ". $ffparms . " | " . $seg;
shell_exec("nohup ". $url." & echo $!");
ob_flush();
flush();
}
If you need to stream out the result of an operation, use the system or passthru methods, or use popen or proc_open to have full control over the input and output of the process.
In general, the PHP scripts which are triggered by your web server are meant to generate a page and exit. They are not the best place to do background tasks such as video encoding, your web server will impost a limit on the programs execution time, and it will be difficult to get status information from your browser (it will appear to hang).
Your best bet is to create a separate daemon process in a language like Python (or PHP) which will run on your computer. When your web scripts need to transcode a video, they can place the necessary information in a database or file which can be polled by the daemon process. The daemon process can also update the database with status information.
In general, your web served pages should be as "non-blocking" as is possible, meaning if something is going to take more than a second or two, do it in the background and create pages on your site to allow the user to view the operations status and manipulate it.
精彩评论