Process – How is a Process Group ID Set

processprocess-groups

I have read that a session's ID is the same as the pid of the process that created the session through the setsid() system call, but I haven't found any information about how a process group ID is set. Is the process group ID the same as the pid of the process that created the process group?

Best Answer

In general, yes, the process group ID is equal to the process ID of the process that created the process group — and that process created the process group by putting itself in the group.

You can find this information in the documentation of the setpgid system call, and of its variant setpgrp. The details have historically varied between BSD and System V. The most common use cases are:

  • A process puts itself into its own process group, and the new PGID is equal to the PID. This can be done with SysV setpgrp() or with setpgid(0, 0) in which either 0 can be replaced by an explicit getpid().
    Note that while the process is putting itself into the group, in practice, this is often done by a launcher (shell, or daemon monitor) before executing the program, i.e. it is done by code in the launcher between fork and execve in the child process.
  • A process puts itself into an existing process group in the same session. Shells do this for pipelines: to run foo | bar in its own process group, a shell typically does something like this:

    1. Set up a pipe.
    2. Fork a process. The child puts itself in its own process group G, closes the read end of the pipe and moves the write end to stdout, then executes foo.
    3. Fork a process. The child puts itself into the existing process group G, closes the write end of the pipe and moves the red end to stdin, then executes bar.

    The call to setpgid may be performed in the parent process instead of or in addition to the child. Doing it in both avoids a race condition in case the second child's initialization overtakes the first child's.

  • A shell with job control normally runs in its own process group. But before exiting or suspending, it returns to its original process group (i.e. it puts itself back into the process group that started it, assuming that group still exists).

The POSIX specification for setpgid describes these use cases. It further explains that there isn't much else that is guaranteed to work. In particular, while old BSD systems allowed a process to join a process group in a different session or to make up a new PGID, this is not the case on most modern systems (including modern BSD).