简体   繁体   English

为什么从子shell开始后台进程/为什么parens(someCommand&)?

[英]Why start a background process from a subshell / why parens in (someCommand &)?

I've come across a script being run as (myDir/myScript.sh arg1 arg2 &) 我遇到了一个运行的脚本(myDir/myScript.sh arg1 arg2 &)

From my understanding, it's running the script in a subshell and also in the background of that sub-shell. 根据我的理解,它在子shell中运行脚本,也在子shell的后台运行。

Will there be any side-effects if I ran the script myDir/myScript.sh arg1 arg2 & without the parenthesis that create the new subshell? 如果我运行脚本myDir/myScript.sh arg1 arg2 &没有创建新子shell的括号,会不会有任何副作用?

The usual reason for running it in a subshell is so that shell doesn't print a message when the background process starts and finishes. 在子shell中运行它的常见原因是shell在后台进程启动和结束时不会打印消息。

Also, if the script ever uses the wait command, it won't wait for background processes started in subshells (a process can only wait for its own children, not grandchildren). 此外,如果脚本曾使用wait命令,它将不会等待在子shell中启动的后台进程(一个进程只能等待自己的子进程,而不是孙进程)。

This also means that the script can't get the exit status of the background process if it's started in a subshell -- you need to use wait to get that. 这也意味着如果脚本在子shell中启动,则脚本无法获取后台进程的退出状态 - 您需要使用wait来获取它。 And the $! $! variable won't be set to the PID of the background process (it's set inside the subshell, not the original shell process). 变量不会被设置为后台进程的PID(它在子shell中设置,而不是原始的shell进程)。

Basically, you use (command&) if the original shell has no need to deal with the background process, it just wants to start it and forget about it. 基本上,你使用(command&)如果原始shell不需要处理后台进程,它只是想启动它而忘记它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM