Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make shell exec run in background while php continues

I have ffmpeg doing a video conversion in a PHP file and it works as it should. The problem is it takes up to a minute for this to finish. I thought it might be easy to do but I can only get it to work in the background when I use just one command (eg single pass conversion without mp4box) like this

exec("nohup " . $ffmpegPath . " -i " . $srcFile . " -f mp4 -vcodec libx264 -crf 27 -s " . $srcWidth . "x" . $srcHeight . " -an -r 20 " . $destFile . ".mp4 > /dev/null 2>&1 &");

The problem is I need to use three different commands to do a proper conversion though. So far my commands look like this in the PHP file and it works, but with a massive delay:

exec($ffmpegPath . " -y -i " . $srcFile . " -f mp4 -pass 1 -passlogfile " . $video_pass_log . " -vcodec libx264 -vpre ipod640 -b:v 2M -bt 4M -an " . $destFile . ".mp4");
exec($ffmpegPath . " -y -i " . $srcFile . " -f mp4 -pass 2 -passlogfile " . $video_pass_log . " -vcodec libx264 -vpre ipod640 -b:v 2M -bt 4M -acodec libfaac -ac 2 -ar 44100 -ab 96k " . $destFile . ".mp4");
exec($mp4boxpath . " -tmp /tmp -hint " . $destFile . ".mp4");

How can I make the shell exec run in background while PHP continues?

like image 241
Jizbo Jonez Avatar asked Jan 22 '12 13:01

Jizbo Jonez


People also ask

Does PHP exec wait until finished?

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.

What is the difference between exec and Shell_exec?

1. The shell_exec() function is an inbuilt function in PHP that is used to execute the commands via shell and return the complete output as a string. The exec() function is an inbuilt function in PHP that is used to execute an external program and returns the last line of the output.

How does Exec work in PHP?

The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.


1 Answers

See Is there a way to use shell_exec without waiting for the command to complete?

Adding > /dev/null 2>/dev/null & will remove the output and runs the command in another process (the & creates the new process, the > and 2> redirects the normal and error output)

like image 166
Jeroen Avatar answered Oct 09 '22 14:10

Jeroen