Should I use “| at now” or ampersand (&) to run th

2019-04-10 15:49发布

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.

标签: php linux shell
2条回答
SAY GOODBYE
2楼-- · 2019-04-10 15:49

The at command is a scheduler that accepts strings from stdin or files that contain commands to run at particular times. Your example:

echo '/usr/bin/php command'| at now

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:

/usr/bin/php command >/dev/null 2>&1 &

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:

/usr/bin/php command &>/dev/null &                 # bash

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.

查看更多
乱世女痞
3楼-- · 2019-04-10 16:07

When you call it with the at command the program is executed in the background by the at 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 a nohoup /usr/bin/php command so the process keeps running when you close your shell.

查看更多
登录 后发表回答