Soheil Yahyaee Soheil Yahyaee - 1 year ago 103
Linux Question

How to run multiple php scripts in background on ubuntu?

I have a webpage that it should run some jobs as php processes in background.
Also, it should be able to identify each process to close it later. Ex. Worker1, Worker2...
How is this achieved? also how to kill the procesees?
The OS is ubuntu.
*Those scripts are always running in the background, so they don't get killed by themselves.

Answer Source

You can put scripts and other shell tasks in background using nohup at the beginning and the & symbol at the end of the command:

~$ nohup php script.php >> /var/tmp/script.log 2>&1 &

Note that with the option 2>&1 you redirects the output (standard error and output) to the standard output, then to a file for logging (here /var/tmp/script.log).

EDIT: with the command jobs you can list the process you have active into your session (here 1797 is the process pid):

~$ jobs -l
[1]+  1797 Running   nohup php script.php >> /var/tmp/script.log 2>&1 &

You can send signals to the process, after you discover the process pid. To kill "nicely" a process (where ${PID} is the process pid):

~$ kill -SIGTERM ${PID}

If the process is stuck you could use the signal SIGKILL (or -9). Note that SIGKILL cannot be intercepted, then the process ends immediately without any "cleaning" operations (closing temporary files, etc). kill -9 ${PID} or kill -SIGKILL ${PID} should be used only as last resource.

Here some theory:

A good course about Gnu/Linux:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download