Linux what is session id

Linux what is session id

Before looking at the Linux implementation, first a general Unix description of threads, processes, process groups and sessions.

A session contains a number of process groups, and a process group contains a number of processes, and a process contains a number of threads.

A session can have a controlling tty. At most one process group in a session can be a foreground process group. An interrupt character typed on a tty («Teletype», i.e., terminal) causes a signal to be sent to all members of the foreground process group in the session (if any) that has that tty as controlling tty.

All these objects have numbers, and we have thread IDs, process IDs, process group IDs and session IDs.

10.1 Processes


Creation

A new process is traditionally started using the fork() system call:

This creates a child as a duplicate of its parent. Parent and child are identical in almost all respects. In the code they are distinguished by the fact that the parent learns the process ID of its child, while fork() returns 0 in the child. (It can find the process ID of its parent using the getppid() system call.)

Termination

Normal termination is when the process does

Abnormal termination is usually caused by a signal.

Collecting the exit code. Zombies

The parent does

A process that has terminated but has not yet been waited for is a zombie . It need only store these two bytes: exit code and reason for termination.

On the other hand, if the parent dies first, init (process 1) inherits the child and becomes its parent.

Signals


Stopping

Some signals cause a process to stop: SIGSTOP (stop!), SIGTSTP (stop from tty: probably ^Z was typed), SIGTTIN (tty input asked by background process), SIGTTOU (tty output sent by background process, and this was disallowed by stty tostop ).

Apart from ^Z there also is ^Y. The former stops the process when it is typed, the latter stops it when it is read.

Signals generated by typing the corresponding character on some tty are sent to all processes that are in the foreground process group of the session that has that tty as controlling tty. (Details below.)

If a process is being traced, every signal will stop it.

Continuing

SIGCONT : continue a stopped process.

Terminating

SIGKILL (die! now!), SIGTERM (please, go away), SIGHUP (modem hangup), SIGINT (^C), SIGQUIT (^\), etc. Many signals have as default action to kill the target. (Sometimes with an additional core dump, when such is allowed by rlimit.) The signals SIGCHLD and SIGWINCH are ignored by default. All except SIGKILL and SIGSTOP can be caught or ignored or blocked. For details, see signal(7) .

10.2 Process groups

Every process is member of a unique process group , identified by its process group ID . (When the process is created, it becomes a member of the process group of its parent.) By convention, the process group ID of a process group equals the process ID of the first member of the process group, called the process group leader . A process finds the ID of its process group using the system call getpgrp() , or, equivalently, getpgid(0) . One finds the process group ID of process p using getpgid(p) .

One may use the command ps j to see PPID (parent process ID), PID (process ID), PGID (process group ID) and SID (session ID) of processes. With a shell that does not know about job control, like ash , each of its children will be in the same session and have the same process group as the shell. With a shell that knows about job control, like bash , the processes of one pipeline. like

Creation

A process pid is put into the process group pgid by

Restrictions on setpgid()

The calling process must be pid itself, or its parent, and the parent can only do this before pid has done exec() , and only when both belong to the same session. It is an error if process pid is a session leader (and this call would change its pgid ).

Typical sequence


Signalling and waiting

One can signal all members of a process group:

One can wait for children in ones own process group:

Foreground process group

Among the process groups in a session at most one can be the foreground process group of that session. The tty input and tty signals (signals generated by ^C, ^Z, etc.) go to processes in this foreground process group.

A process can determine the foreground process group in its session using tcgetpgrp(fd) , where fd refers to its controlling tty. If there is none, this returns a random value larger than 1 that is not a process group ID.

A process can set the foreground process group in its session using tcsetpgrp(fd,pgrp) , where fd refers to its controlling tty, and pgrp is a process group in the its session, and this session still is associated to the controlling tty of the calling process.

How does one get fd ? By definition, /dev/tty refers to the controlling tty, entirely independent of redirects of standard input and output. (There is also the function ctermid() to get the name of the controlling terminal. On a POSIX standard system it will return /dev/tty .) Opening the name of the controlling tty gives a file descriptor fd .

Читайте также:  What are filters in linux

Background process groups

All process groups in a session that are not foreground process group are background process groups . Since the user at the keyboard is interacting with foreground processes, background processes should stay away from it. When a background process reads from the terminal it gets a SIGTTIN signal. Normally, that will stop it, the job control shell notices and tells the user, who can say fg to continue this background process as a foreground process, and then this process can read from the terminal. But if the background process ignores or blocks the SIGTTIN signal, or if its process group is orphaned (see below), then the read() returns an EIO error, and no signal is sent. (Indeed, the idea is to tell the process that reading from the terminal is not allowed right now. If it wouldn’t see the signal, then it will see the error return.)

When a background process writes to the terminal, it may get a SIGTTOU signal. May: namely, when the flag that this must happen is set (it is off by default). One can set the flag by

Orphaned process groups

The process group leader is the first member of the process group. It may terminate before the others, and then the process group is without leader.

A process group is called orphaned when the parent of every member is either in the process group or outside the session . In particular, the process group of the session leader is always orphaned.

If termination of a process causes a process group to become orphaned, and some member is stopped, then all are sent first SIGHUP and then SIGCONT.

The idea is that perhaps the parent of the process group leader is a job control shell. (In the same session but a different process group.) As long as this parent is alive, it can handle the stopping and starting of members in the process group. When it dies, there may be nobody to continue stopped processes. Therefore, these stopped processes are sent SIGHUP, so that they die unless they catch or ignore it, and then SIGCONT to continue them.

Note that the process group of the session leader is already orphaned, so no signals are sent when the session leader dies.

Note also that a process group can become orphaned in two ways by termination of a process: either it was a parent and not itself in the process group, or it was the last element of the process group with a parent outside but in the same session. Furthermore, that a process group can become orphaned other than by termination of a process, namely when some member is moved to a different process group.

10.3 Sessions

Every process group is in a unique session . (When the process is created, it becomes a member of the session of its parent.) By convention, the session ID of a session equals the process ID of the first member of the session, called the session leader . A process finds the ID of its session using the system call getsid() .

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 . (And when that fails, there was no controlling tty.) Given a file descriptor for the controlling tty, one may obtain the SID using tcgetsid(fd) .

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.

Creation

A new session is created by

The restriction that the current process must not be a process group leader is needed: otherwise its PID serves as PGID of some existing process group and cannot be used as the PGID of a new process group.

Getting a controlling tty

How does one get a controlling terminal? Nobody knows, this is a great mystery.

The System V approach is that the first tty opened by the process becomes its controlling tty.

The BSD approach is that one has to explicitly call

Linux tries to be compatible with both, as always, and this results in a very obscure complex of conditions. Roughly:

The TIOCSCTTY ioctl will give us a controlling tty, provided that (i) the current process is a session leader, and (ii) it does not yet have a controlling tty, and (iii) maybe the tty should not already control some other session; if it does it is an error if we aren’t root, or we steal the tty if we are all-powerful.

Opening some terminal will give us a controlling tty, provided that (i) the current process is a session leader, and (ii) it does not yet have a controlling tty, and (iii) the tty does not already control some other session, and (iv) the open did not have the O_NOCTTY flag, and (v) the tty is not the foreground VT, and (vi) the tty is not the console, and (vii) maybe the tty should not be master or slave pty.

Getting rid of a controlling tty

If a process wants to continue as a daemon, it must detach itself from its controlling tty. Above we saw that setsid() will remove the controlling tty. Also the ioctl TIOCNOTTY does this. Moreover, in order not to get a controlling tty again as soon as it opens a tty, the process has to fork once more, to assure that it is not a session leader. Typical code fragment:

Читайте также:  Как обновить windows 10 ltsc до версии pro

See also daemon(3) .

Disconnect

If the terminal goes away by modem hangup, and the line was not local, then a SIGHUP is sent to the session leader. Any further reads from the gone terminal return EOF. (Or possibly -1 with errno set to EIO.)

If the terminal is the slave side of a pseudotty, and the master side is closed (for the last time), then a SIGHUP is sent to the foreground process group of the slave side.

When the session leader dies, a SIGHUP is sent to all processes in the foreground process group. Moreover, the terminal stops being the controlling terminal of this session (so that it can become the controlling terminal of another session).

Thus, if the terminal goes away and the session leader is a job control shell, then it can handle things for its descendants, e.g. by sending them again a SIGHUP. If on the other hand the session leader is an innocent process that does not catch SIGHUP, it will die, and all foreground processes get a SIGHUP.

10.4 Threads

A process can have several threads. New threads (with the same PID as the parent thread) are started using the clone system call using the CLONE_THREAD flag. Threads are distinguished by a thread ID (TID). An ordinary process has a single thread with TID equal to PID. The system call gettid() returns the TID. The system call tkill() sends a signal to a single thread.

Example: a process with two threads. Both only print PID and TID and exit. (Linux 2.4.19 or later.)

Источник

Ponyhof

Dysfunctional Programming

Session-Management on Linux

One thing I always admired on linux is fast session-switching. A simple key-press (ctrl+alt+Fx) and I can ditch my current session to switch to another one. While in principle session-interaction is fairly simple, you can easily get it wrong (as can be seen with XMir). But how exactly does session management work today? And how did systemd-logind change this situation?

First, we need to define a session. A session is a group of processes running under control of a single user. Only a single session is active on a system (more precisely on a seat; discussed below) and a user can only interact with the active (or foreground) session. A session can start and stop processes, but it cannot escape from the session. In other words, all started processes will always belong to the session they were started in. Only system-daemons (which are not attached to a session) can spawn new sessions.

A session usually has different user-daemons which provide services for the session. For instance, the X-Server provides graphics access to other session-processes, pulseaudio provides audio-access. Then there is a central process which controls and monitors a session. Whenever a session is spawned, this process is the first process that is created. It initializes the session, spawns other management processes and optionally restarts them if they crash. It might also exit once the session was initialized if no process-monitoring is required. An example would be gnome-session.

1) Session Management

Historically, every process on a system has a session-id which defines the session a process belongs to. The setsid() system call allows to create a new session. However, with systemd-logind a new more-versatile concept was introduced. To understand this, we need to first look at seats .

Seats

Multi-seat setup (source: Wikipedia)

On normal systems only a single seat exists (called seat0). But more seats can be created on request. A seat is a virtual object that describe a physical interface to a system. The combination of a monitor plus keyboard and mouse form a usual seat. One user can interact with the system through this seat. If you attach another monitor plus keyboard and mouse, another user can interact with the system in parallel via this new seat (eg., called seat1). It is important to note that these seats are independent of each other. The pictures you get on the monitors are different and keyboard input from one seat doesn’t affect the other.

Any device connected to your system can be attached to a seat, but only to one seat at a time! If a device is attached to seat, it cannot be used by processes running on another seat. Obviously, input devices, sound-devices and monitors are usually attached to a seat. Network-interfaces, for example, can be left unattached so all seats can share an internet-connection. It is up to the system-administrator to decide which devices to attach to which seat, or whether to leave them as global devices that can be shared.

Bootup

During system-boot, systemd starts several daemons to manage a system. All these daemons are global and not attached to a seat or session. This also means, these daemons must not access devices attached to a seat. Among these daemons is also systemd-logind, which is responsible for session and seat management.

To allow user interaction, systemd needs to automatically spawn a new session for each seat. This is usually a login-session (like gdm, kdm or LightDM) but might also be configured as auto-login and spawn directly a user-session like gnome-session. In case of a login-session, the greeter draws login and password fields and after verifying the input, it instructs systemd to spawn a user-session. Note that the greeter cannot start the user-session itself as it already runs in a session (you cannot escape your session, remember?).

Читайте также:  Включить сетевое обнаружение windows 10 что это

But what exactly does systemd do to control sessions?

Sessions

Via kernel interfaces (namely cgroups) systemd can reliably track processes and their childs. Whenever systemd is instructed to start a new session, it first verifies the caller is allowed to do that and then it spawns the first process for the session. Internally, it attaches a new session-id to this process, saves the seat this session is run on and some other maintenance data. Whenever this session process creates new processes, systemd can use cgroups to track these. So it always knows which session a process belongs to.

The first process for a session is responsible of initializing the session. In case of gnome-session, it spawns the X-Server, some gnome-specific maintenance daemons and then monitors the session in case something goes wrong. You can now interact with this session (normally through the X-Server) and do your daily work.

A session can explicitly instruct systemd to close itself. However, this will only mark it as dead. Once all processes of a session exited, the session is automatically cleaned up and removed.

2) Case-Study: Text-mode sessions

Text-mode interface (source: Wikipedia)

As a concrete non-trivial scenario, I’ll explain how text-mode sessions integrate with this. First, we need to know that virtual-terminals are basically a combination of input devices and a monitor. They can be accessed via /dev/tty (where is between 1 and 63; the other /dev/ttyXY devices are no VTs!). If you read from them, you get input from connected keyboards, if you write to them, the kernel displays it as text on the monitor. Some rather complex control-sequences are available to do colors or more, but that’s beyond the scope. VTs are always bound to seat0. So only sessions on this seat can use VTs (which means, classic text-mode is only available on seat0).

Text-mode sessions are special in that they are not spawned by a login-session. systemd-logind spawns /bin/agetty right during boot for each VT (you can configure how many of the 63 possible should be started). agetty is running as system daemon and not in a session! However, it is bound to seat0, obviously. agetty initializes the VT and runs /bin/login. login then writes a greeter to the VT and reads username plus password from it. As you might notice, this is problematic as it accesses devices attached to a seat even though it’s not running in a session. But due to the design of VTs, this cannot be easily avoided.

Once login verified the user-input, it instructs systemd to start the given user-session in text-mode. It looks up the initial process in /etc/passwd (let’s assume it is /bin/bash) and runs it. So bash is the controlling process in this session. It also substitutes the X-Server in that it provides user-interaction (in text mode rather than graphics). It allows to switch between different processes (ctrl+Z, fg, bg and jobs) and allows starting other session-daemons during initialization (via .bashrc).

So while text-mode feels a lot different, it is in fact very similar to graphics mode and is internally handled almost equally.

3) Multi-Session

We now understand what a session is, how they are created and how a user interacts with them. However, we haven’t discussed what happens if there are multiple sessions on a seat.

On current systems, multiple sessions are only allowed on seat0 if VTs are enabled (which is usually the case). That means, on all other seats, once you spawned a session, you have to stick with it. You cannot ctrl+alt+Fx away from the session (the reason for this is historical and we’re about to change this). However, you can close the session and then start a new one.

But if we assume our seat supports multiple sessions, how does that work? systemd-logind is responsible to manage and track sessions. Therefore, it keeps an Active attribute for each session. It’s a boolean value that defines whether the session is currently active or not. systemd-logind takes care that always at most one session is active. If no session runs on a seat, no session might be active (also in other situations which we ignore here as it’s an implementation detail). Additionally, systemd-logind sets the correct access-restrictions on devices attached to a seat so only the active session can access these devices. This guarantees that no background session interferes with foreground activity.

To switch between sessions, each session has to listen for special keyboard input (normally ctrl+alt+Fx) and instruct systemd-logind to switch to another session once it’s pressed. Today, this is implemented in the X-Server or, if no x-server runs in the session, by the underlying VT. You can also send a dbus call to systemd-logind directly to perform the session-switch (see loginctl activate ).

So for proper multi-session support, a login-session spawns a user-session during login but stays active in background. A user can now switch between the user-session and the login-session and optionally spawn additional session by logging in again. Session processes can listen for dbus signals from systemd-logind to be notified when they are activated or deactivated. This allows them to go asleep while being in background and start up again once being put in foreground.

For an in-depth view on session-switching, see this followup article.

Источник

Оцените статью