使用输入/输出重定向在后台运行进程 [英] Running a process in the background with input/output redirection
问题描述
我很想知道'&'在哪里是否有所作为进程具有输入/输出重定向以在后台运行进程时,在代码中使用运算符
I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background
就在后台运行进程而言,这些代码行之间有什么区别/是否存在任何区别.如果有的话,我该如何确定会有什么不同?
What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I determine what the differences are going to be?
setsid python script.py < /dev/zero &> log.txt &
setsid python script.py < /dev/zero & > log.txt &
setsid python script.py < /dev/zero > log.txt &
setsid python script.py & < /dev/zero > log.txt
推荐答案
控制操作符
这里&
有两种用途.一种是所谓的控制操作员.每个命令都由诸如&
,;
或<newline>
的控制运算符终止.它们之间的区别在于;
和<newline>
在前台运行命令,而&
在后台运行.
Control operator
There are two uses of &
here. One is as a so-called control operator. Every command is terminated by a control operator such as &
, ;
or <newline>
. The difference between them is that ;
and <newline>
run the command in the foreground and &
does it in the background.
setsid python script.py < /dev/zero & > log.txt &
setsid python script.py & < /dev/zero > log.txt
因此,这两行实际上分别执行两个命令.第一个等效于两个命令:
These two lines, therefore, actually execute two commands each. The first is equivalent to the two commands:
setsid python script.py < /dev/zero &
> log.txt &
第二个等效于:
setsid python script.py &
< /dev/zero > log.txt
如果您想知道,是的,> log.txt
和< /dev/zero > log.txt
都是合法命令.缺少命令名称,它们仅处理重定向:每个命令都会创建一个名为log.txt
的空文件.
If you're wondering, yes, > log.txt
and < /dev/zero > log.txt
are both legal commands. Lacking a command name, they simply process the redirections: each one creates an empty file called log.txt
.
setsid python script.py < /dev/zero &> log.txt &
此版本的&>
与& >
的版本不同. &>
没有空格是bash中特殊的重定向操作符,它可以同时重定向stdout和stderr.
This version with &>
is different from the one with & >
. &>
without a space is a special redirection operator in bash that redirects both stdout and stderr.
setsid python script.py < /dev/zero > log.txt &
此最终版本与先前版本相似,只是它仅将stdout重定向到log.txt
. stderr继续前往终端.
This final version is similar to the previous one except it only redirects stdout to log.txt
. stderr continues to go to the terminal.
这篇关于使用输入/输出重定向在后台运行进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!