简体   繁体   中英

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 &)

From my understanding, it's running the script in a subshell and also in the background of that sub-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?

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.

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).

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. 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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