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.
-
4Welcome to Stack Overflow, @Soheil Yahyaee. I know this is probably not what you wanted to see, but here we like to see what you have tried first and then we can jump in and help you. Give it a try your self, post some code and tell us where you're getting stuck.Olivier De Meulder– Olivier De Meulder2015-09-25 14:31:09 +00:00Commented Sep 25, 2015 at 14:31
-
What have you tried so far? Where are you stuck? Why not run them like every other script?Nico Haase– Nico Haase2021-06-18 07:29:38 +00:00Commented Jun 18, 2021 at 7:29
1 Answer
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:
Input/Output redirection:
Some courses to become GNU/linux system administrators:
4 Comments
2>&1 you can redirect the standard error on the standard output. The answer is modified. A link about redirection: tldp.org/LDP/abs/html/io-redirection.html