The Linux Programming Interface

(nextflipdebug5) #1
Process Groups, Sessions, and Job Control 707

If a process has a controlling terminal, opening the special file /dev/tty obtains
a file descriptor for that terminal. This is useful if standard input and output are
redirected, and a program wants to ensure that it is communicating with the con-
trolling terminal. For example, the getpass() function described in Section 8.5 opens
/dev/tty for this purpose. If the process doesn’t have a controlling terminal, open-
ing /dev/tty fails with the error ENXIO.


Removing a process’s association with the controlling terminal


The ioctl(fd, TIOCNOTTY) operation can be used to remove a process’s association
with its controlling terminal, specified via the file descriptor fd. After this call,
attempts to open /dev/tty will fail. (Although not specified in SUSv3, the TIOCNOTTY
operation is supported on most UNIX implementations.)
If the calling process is the controlling process for the terminal, then as for the
termination of the controlling process (Section 34.6.2), the following steps occur:



  1. All processes in the session lose their association with the controlling terminal.

  2. The controlling terminal loses its association with the session, and can there-
    fore be acquired as the controlling process by another session leader.

  3. The kernel sends a SIGHUP signal (and a SIGCONT signal) to all members of the
    foreground process group, to inform them of the loss of the controlling terminal.


Establishing a controlling terminal on BSD


SUSv3 leaves the manner in which a session acquires a controlling terminal
unspecified, merely stating that specifying the O_NOCTTY flag when opening a terminal
guarantees that the terminal won’t become a controlling terminal for the session.
The Linux semantics that we have described above derive from System V.
On BSD systems, opening a terminal in the session leader never causes the ter-
minal to become a controlling terminal, regardless of whether the O_NOCTTY flag is
specified. Instead, the session leader uses the ioctl() TIOCSCTTY operation to explicitly
establish the terminal referred to by the file descriptor fd as the controlling terminal:


if (ioctl(fd, TIOCSCTTY) == -1)
errExit("ioctl");

This operation can be performed only if the session doesn’t already have a control-
ling terminal.
The TIOCSCTTY operation is also available on Linux, but it is not widespread on
other (non-BSD) implementations.


Obtaining a pathname that refers to the controlling terminal: ctermid()


The ctermid() function returns a pathname referring to the controlling terminal.


#include <stdio.h> /* Defines L_ctermid constant */

char *ctermid(char *ttyname);
Returns pointer to string containing pathname of controlling terminal,
or NULL if pathname could not be determined
Free download pdf