The Linux Programming Interface

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

On a few UNIX implementations (e.g., HP-UX 11), getsid() can be used to
retrieve the session ID of a process only if it is in the same session as the calling
process. (SUSv3 permits this possibility.) In other words, the call merely serves,
by its success or failure (EPERM), to inform us if the specified process is in the
same session as the caller. This restriction doesn’t apply on Linux or on most
other implementations.

If the calling process is not a process group leader, setsid() creates a new session.


The setsid() system call creates a new session as follows:


z The calling process becomes the leader of a new session, and is made the
leader of a new process group within that session. The calling process’s process
group ID and session ID are set to the same value as its process ID.


z The calling process has no controlling terminal. Any previously existing con-
nection to a controlling terminal is broken.


If the calling process is a process group leader, setsid() fails with the error EPERM. The
simplest way of ensuring that this doesn’t happen is to perform a fork() and have
the parent exit while the child carries on to call setsid(). Since the child inherits its
parent’s process group ID and receives its own unique process ID, it can’t be a pro-
cess group leader.
The restriction against a process group leader being able to call setsid() is neces-
sary because, without it, the process group leader would be able to place itself in
another (new) session, while other members of the process group remained in the
original session. (A new process group would not be created, since, by definition,
the process group leader’s process group ID is already the same as its process ID.)
This would violate the strict two-level hierarchy of sessions and process groups,
whereby all members of a process group must be part of the same session.


When a new process is created via fork(), the kernel ensures not only that it has a
unique process ID, but also that the process ID doesn’t match the process group
ID or session ID of any existing process. Thus, even if the leader of a process
group or a session has exited, a new process can’t reuse the leader’s process ID
and thereby accidentally become the leader of an existing session or process
group.

Listing 34-2 demonstrates the use of setsid() to create a new session. To check that it no
longer has a controlling terminal, this program attempts to open the special file /dev/
tty (described in the next section). When we run this program, we see the following:


$ ps -p $$ -o 'pid pgid sid command' $$ is PID of shell
PID PGID SID COMMAND
12243 12243 12243 bash PID, PGID, and SID of shell
$ ./t_setsid
$ PID=12352, PGID=12352, SID=12352
ERROR [ENXIO Device not configured] open /dev/tty

#include <unistd.h>

pid_t setsid(void);
Returns session ID of new session, or (pid_t) –1 on error
Free download pdf