Difference between ( ) & and ( &)?
Asked Answered
E

1

9

I'm wondering what's the difference between these two grammar in bash: ( &) and ( ) &.

The only difference that I noticed is, (tty &) will return "not a tty" while (tty) & will return the current tty name, but why?

To give an example, should I run (setsid startx &) or (setsid startx) &?

Elfreda answered 16/3, 2014 at 3:35 Comment(0)
H
6

In the case of

(tty &)

a subshell is started which starts another tty process in the background without job control and terminal, hence there is a "not a tty" error. The tty process becomes detached with PPID 1

In the case of

(tty) &

a subshell is started and runs in the background. This background shell starts a tty process and after tty finishes and reports to the terminal, the subshell finishes in the background.

--

tty is a simple command. Whether or not a particular command (like startx) needs a ( ... &) construct to become detached / disowned from a parent process depends on the command itself. There are a number of ways for a process to in turn start a subprocess and detach that, so the command may not need it.

Hairdo answered 16/3, 2014 at 16:36 Comment(2)
If X & runs X without a controlling terminal, it seems (tty)& would run the subshell without a controlling terminal, and therefore the tty command wouldn't have a controlling terminal either. Is the difference due to whether the background process is started by the session leader?Animation
@VaughnCato There are a number of ways for a process to in turn start a subprocess and detach it. It also matters if a command is executed from an interactive shells or not. (tty)& will not run without a controlling terminal if it is executed from an interactive shell. You can easily test this by replacing tty with sleep 60 for example and checking with ps.Hairdo

© 2022 - 2024 — McMap. All rights reserved.