Why group leader can't able to create the session. but, other than the group leader able to create the session?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
main() {
int pid;
int ppid=getppid();
if ( setsid() < 0)
perror("ERROR");
if((pid=fork()) == 0)
{
printf("proces1=%d %d\n",getpid(),getpgrp());
int s=getpgrp();
//setpgid(pid,pid);
if (setpgid(pid,0) < 0)
perror("ERROR");
printf("group after proces=%d %d\n",getpid(),getpgrp());
exit(0);
}
wait(0);
printf("group after proces=%d %d\n",getpid(),getpgrp());
}
Please explain.
Short answer
Forbidding setsid()
in a process group leader is required by POSIX:
The
setsid()
function shall create a new session, if the calling process is not a process group leader.
It is required to ensure that all members of a process group are members of the same session.
Long answer
Process group ID is PID of process group leader. Session ID is PID of session leader. After successful setsid()
call, process group ID, session ID and PID should be the same.
However, for the process group leader, process group ID is already equal to PID. If it would be able to call setsid()
, it's process group ID remains the same, so that:
Thus, in this case we have a process group with members belonging to different sessions. POSIX wants to forbid this situation.
Why?
Process groups and sessions were invented for job control. Process groups are used to determine foreground and background groups, so that foreground group will receive signals from terminal.
To implement this, terminal tracks its current foreground process group and sends signal to that group when some event occurs.
But this assumes that all processes from any given process group share the same controlling terminal, so that signals sent by terminal are meaningful for them.
Controlling terminal is shared by the following rules:
Thus, if we require all members of a process group to share the same controlling terminal, we also should require them to be members of the same session.
Reference
See "The Linux Programming Interface", Chapter 34 (Process Groups, Sessions, and Job Control).