I've been looking through the answers about running php script in a background and they seem to be spreading in two ways.
Some people suggest using this (or something similar):
/usr/bin/php command >/dev/null 2>&1 &
Other suggest using "at" command:
echo '/usr/bin/php command'| at now
What are the major differences about theese two methods? What are the pros and cons?
What I'm trying to do is when user submits the form, I need to run a few-minutes long script, that should obviously be run in background. I've tried both ways and they both worked for me, but I'm not sure which to pick.
The at command is a scheduler that accepts strings from stdin or files that contain commands to run at particular times. Your example:
Is giving the 'at' command your command as a string and scheduling it to be run immediately.
The first method is the the typical way to background a process via the shell:
The "> /dev/null" part of that is telling the shell to send the stdout of your command to /dev/null, and the "2>&1" part of that is saying to send the output of stderr of your command to stdout (which then goes to /dev/null). Together, they suppress output. You can actually do that in one step with:
The '&' at the end of that is what tells the shell to background the process.
The pros of using 'at' is the flexability of scheduling your command to be run at other times than now (among other things). Read the man page for it. The cons are that it may not be installed on all systems.
The pros of using & via shells is that there is no overhead on the backgrounding per se. When using 'at' to run a command immediately is kindof overkill, since it involve creating a new process for at, scheduling the command, realizing that it's set to be run now, and then running it in the background. Whereas running the command with "&" in the shell will simply run that command in the background.
When you call it with the
at
command the program is executed in the background by theat
daemon.When you use
&
the process is still attached to the current shell. When you close the shell, the process is terminated. You could also do anohoup /usr/bin/php command
so the process keeps running when you close your shell.