setsid() — Create session, set process group ID
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1 |
both |
Format
#define _POSIX_SOURCE
#include <unistd.h>
pid_t setsid(void);
General description
Creates a new session with the calling process as its session leader. The caller becomes the process group leader of a new process group. The calling process must not be a process group leader already. The caller does not have a controlling terminal.
The process group ID (PGID) of the new process group is equal to the process ID (PID) of the caller. The caller starts as the only process in the new process group and in the new session.
Returned value
If successful, setsid() returns the value of the caller's new PGID.
If unsuccessful,
setsid() returns -1 and sets errno to one of the following values:
- Error Code
- Description
- EPERM
- One of the following error conditions exists:
- The caller is already a process group leader.
- The caller's PID matches the PGID of some other process.
Example
CELEBS10
/* CELEBS10
This example creates a new session.
*/
#define _POSIX_SOURCE
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
main() {
pid_t pid;
int p[2];
char c='?';
if (pipe(p) != 0)
perror("pipe() error");
else
if ((pid = fork()) == 0) {
printf("child's process group id is %d\n", (int) getpgrp());
write(p[1], &c, 1);
setsid();
printf("child's process group id is now %d\n", (int) getpgrp());
exit(0);
}
else {
printf("parent's process group id is %d\n", (int) getpgrp());
read(p[0], &c, 1);
sleep(5);
}
}
Output
child's process group id is 262152
child's process group id is now 262150
parent's process group id is 262152