我应该使用" |现在"或&符(&)在后台运行脚本? [英] Should I use "| at now" or ampersand (&) to run the script in background?

查看:44
本文介绍了我应该使用" |现在"或&符(&)在后台运行脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关在后台运行php脚本的答案,它们似乎以两种方式传播.

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 &

其他建议使用"at"命令:

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.

推荐答案

at命令是一个调度程序,它接受来自stdin或包含在特定时间运行的命令的文件中的字符串.您的示例:

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

正在将'at'命令作为字符串提供给您,并安排它立即运行.

Is giving the 'at' command your command as a string and scheduling it to be run immediately.

第一种方法是通过shell后台进程的典型方法:

The first method is the the typical way to background a process via the shell:

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

其中的>/dev/null"告诉外壳程序将命令的stdout发送到/dev/null,而其中的"2>& 1"部分则表示要发送命令的输出.您的命令stderr到stdout(然后转到/dev/null).它们一起抑制了输出.您实际上可以一步完成此操作:

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.

使用'at'的优点是可以灵活地安排您的命令在当前时间以外的时间运行(以及其他功能).阅读手册页.缺点是可能未在所有系统上都安装它.

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.

使用&的优点通过shell进行操作,背景本身没有任何开销.使用"at"立即运行命令时有点过头,因为它涉及为at创建一个新进程,安排该命令,意识到它已设置为现在运行,然后在后台运行.而使用&"运行命令在外壳中只需在后台运行该命令即可.

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.

这篇关于我应该使用" |现在"或&符(&)在后台运行脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆