Open In App

How to execute a background process in PHP ?

Last Updated : 12 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 to run process in background
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);
}
  
// "sleep 5" process will run in background
run("sleep 5");
  
print_r("current processID is: ".getmypid());
  
?>


Output

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads