Linux – Is a Session Leader the Only Process in Its Group?

linuxprocesssessionshell

The following diagram from APUE leads me to wonder: in a process session, does the process group of the session leader contain only the session leader and no other process?

  • Any process created by fork() will inherit the same process group and session from its parent. So can the session leader fork arbitrary number of processes into its own process group?

  • For example, is a shell (when it is a session leader) the only process in its process group? If yes, is it because when the shell forks a child process, the child is initially in the same process group as the shell, but then immediately starts a new process group by calling setpgid() ?

Thanks.

enter image description here

Best Answer

No, there's no such restriction. If it was the case, commands that don't implement job control (in practice, only shells do) wouldn't be able to fork a process (as child processes inherit the process group) when started as xterm -e that-command for instance.

Even when the session leader is an interactive shell with job control enabled, you can have other processes in its group.

Running:

xterm -e 'sleep 1000 & exec zsh'

And in that xterm:

  PID  PGID   SID TTY          TIME CMD
14003 14003 14003 pts/20   00:00:00 zsh
14004 14003 14003 pts/20   00:00:00 sleep
14012 14012 14003 pts/20   00:00:00 ps

Most commands run from an interactive shell are run in separate process groups, but it's not the case for all.

For instance, in bash:

$ exec 3< <(sleep 1000)
$ ps -j
  PID  PGID   SID TTY          TIME CMD
13913 13913 13913 pts/19   00:00:00 bash
14136 13913 13913 pts/19   00:00:00 bash
14137 13913 13913 pts/19   00:00:00 sleep
14138 14138 13913 pts/19   00:00:00 ps

Or the processes started as part of prompt expansions:

$ PS1=$'$(ps -j)\n$ '
  PID  PGID   SID TTY          TIME CMD
14212 14212 14212 pts/18   00:00:00 bash
14292 14212 14212 pts/18   00:00:00 ps
$