Tim
Tim

Reputation: 99418

How would the existing processes in the session learn about and acquire the controlling terminal, just acquired by the session leader?

In the first scenario, a process calls setsid() to start a new session and become its leader, and calls open() to connect to a controlling terminal. Then the session leader goes on to fork() child processes, and the children will inherit the file descriptor to the controlling terminal.

In the second scenario, if a session already has multiple processes and but has no controlling terminal, and then the leader creates a connection to a controlling terminal, what about the other processes in the session:

Thanks.

Originated from https://unix.stackexchange.com/questions/446207/for-a-process-what-are-the-differences-between-a-controlling-terminal-and-non-c

Upvotes: 3

Views: 301

Answers (1)

zwol
zwol

Reputation: 140569

The controlling terminal is described in a lot of documentation as a property of an entire session, but it's really a property of each individual process, which is inherited from parent to child in fork. A process has to be a session leader to attach itself to a controlling tty, but any process can detach from its controlling tty, if it has one, with the TIOCNOTTY ioctl. So the system is set up to handle processes that are in a session but not attached to a controlling tty.

In your "second scenario", processes that the session leader forked before attaching to a controlling tty do not get attached to that tty along with it. This means that they are not entirely part of the session, in the same way that processes that have detached from the controlling tty are not entirely part of the session: they can't be put into the foreground with tcsetpgrp, they cannot open /dev/tty, they don't receive SIGHUP if the controlling tty hangs up, etc. Processes that the session leader forks after it attaches a controlling tty, on the other hand, will inherit it as usual.

(As a general rule, in Unix, operations that manipulate the calling process's state never have any effect on any other process, even if it seems like they ought to; also as a general rule, when we say such and such is inherited over a fork, we mean that piece of state is copied into the child, not shared between parent and child. An important exception is "open file description"s, which are shared. If you have a regular file open in a process that forks, and the child calls lseek on its inherited file descriptor, the parent will see the seek pointer move.)

Upvotes: 4

Related Questions