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

kawing-chiu
  • 2,675
  • 1
  • 14
  • 10

1 Answers1

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.

Scrutinizer
  • 9,608
  • 1
  • 21
  • 22
  • 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? – Vaughn Cato Mar 16 '14 at 19:17
  • @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`. – Scrutinizer Mar 16 '14 at 20:04