What is a session leader

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-04-24

Most precisely, it is a process where PID = SID (session ID)

What is session ID (SID)?

Trivially, it is the ID of that process session. It is inherited by child processes from parent process

Encapsulates not just a bunch of processes, but a bunch of process groups. Normally, a shell will be a session leader, and every pipeline executed by that shell will be a process group. This is to make it easy to kill the children of a shell when it exits. (See exit(3) for the gory details.)

A session is often set up by a login process. The terminal on which one is logged in then becomes the controlling tty of the session. All processes that are descendants of the login process will in general be members of the session.

Connection with tty

Every session may have a controlling tty, that then also is called the controlling tty of each of its member processes. A file descriptor for the controlling tty is obtained by opening /dev/tty. For the controlling tty, one may obtain the SID using tcgetsid(fd).

Explain why it must be avoided with daemons:

(Best guess) Because we don't want the daemon to get a kill signal when the user leaves the terminal (this signal is SIGHUP; that gets sent to all processes in the process group when the terminal disconnects (hangs up - hence HUP).) The idea is that daemons should last longer.

For both these reasons, we call setsid() on processes to be daemonized. This makes these processes their own session leaders. (It also puts the process in a new process group since processes from the same group must be in the same session - since we switched session, we have to switch process group)

aka it is sorta similar to nohup $COMMAND

Resources