Php run shell command in background

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.

asked Oct 5, 2011 at 7:11

1

$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

answered Oct 5, 2011 at 7:50

Matthieu NapoliMatthieu Napoli

46.3k44 gold badges163 silver badges252 bronze badges

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

32.6k48 gold badges170 silver badges302 bronze badges

answered May 24, 2012 at 11:09

Eduardo RussoEduardo Russo

3,9032 gold badges20 silver badges36 bronze badges

0

Not the answer you're looking for? Browse other questions tagged php linux shell or ask your own question.

What is the background process and why do we need them?

A process that runs behind the scenes (i.e. in the background) and without user intervention is called the background process. Debug/error logging, monitoring any system with grafana or kibana,  user notification,  scheduling jobs, and publishing some data are a typical example of background process. The background process is usually a child process created by a control process for processing a computing task. After creation, the child process will run on its own, performing the task independent of the parent process’s state.

There are a lot of ways to run a job in the background. Crontab, multithreading in java, go routines in golang are examples of such cases. 

To run a process in ubuntu, we simply type a command on the terminal. For example, to run a PHP file, we use the following command :

php filename.php

In PHP, we can not directly run any process job in the background even if the parent job terminates. Before we get to know how to run the process in the background let’s know how to execute terminal commands from PHP script or program. To achieve this functionality we can use exec and shell_exec functions in PHP.

A sample command to run any command with PHP is:

PHP

<?php 

  shell_exec(sprintf('%s > /dev/null 2>&1 &', "echo 4"));

?>

There are the important points of the above code:

  • The output (STDOUT) of the script must be directed to a file. /dev/null indicates that we are not logging the output.
  • The errors (STDERR) also must be directed to a file. 2>&1 means that STDERR is redirected into STDOUT and therefore into the nirvana.
  • The final & tells the command to execute in the background.

 We can check the status of any running process with command ps, for example:

ps -ef

So, to run any background process from PHP, we can simply use either exec or shell_exec function to execute any terminal command and in that command, we can simply add & at the last so that, the process can run in the background.

Below is the implementation of the above approach:

PHP

<?php

function run($command, $outputFile = '/dev/null') {

    $processId = shell_exec(sprintf(

        '%s > %s 2>&1 & echo $!',

        $command,

        $outputFile

    ));

      print_r("processID of process in background is: "

        . $processId);

}

run("sleep 5");

print_r("current processID is: ".getmypid());

?>

Output

processID of process in background is: 19926
current processID is: 19924


How do I run a shell in the background?

Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.

Can PHP run in the background?

So, to run any background process from PHP, we can simply use either exec or shell_exec function to execute any terminal command and in that command, we can simply add & at the last so that, the process can run in the background.

How do I run a PHP command in terminal?

You just follow the steps to run PHP program using command line..
Open terminal or command line window..
Goto the specified folder or directory where php files are present..
Then we can run php code using the following command: php file_name.php..

What is Shell_exec?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking.