Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1 |
both |
#define _POSIX_SOURCE
#include <unistd.h>
int setpgid(pid_t pid, pid_t pgid);
Sets the process group ID (PGID) of a process within the session of the calling process, so you can reassign a process to a different process group, or start a new process group with the specified process as its group leader.
pid_t pid is the process ID (PID) of the process whose PGID you want to change. This must either be the caller of setpgid() or one of its children, and it must be in the caller's session. It cannot be the PID of a session leader. If pid is zero, the system uses the PID of the process calling setpgid().
pid_t pgid is the new PGID you want to assign to the process identified by pid. If pgid indicates an existing process group, it must be in the caller's session. If pgid is zero, the system uses the PID of the process indicated by pid as the ID for the new process group. The new group is created in the caller's session.
If successful, setpgid() returns 0.
⁄* CELEBS09
This example sets the PGID.
*⁄
#define _POSIX_SOURCE
#include <unistd.h>
#include <sys⁄types.h>
#include <stdio.h>
main() {
pid_t pid;
int p1[2], p2[2];
char c='?';
if (pipe(p1) != 0)
perror("pipe() #1 error");
else if (pipe(p2) != 0)
perror("pipe() #2 error");
else
if ((pid = fork()) == 0) {
printf("child's process group id is %d\n", (int) getpgrp());
write(p2[1], &c, 1);
puts("child is waiting for parent to complete task");
read(p1[0], &c, 1);
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(p2[0], &c, 1);
printf("parent is performing setpgid() on pid %d\n", (int) pid);
if (setpgid(pid, 0) != 0)
perror("setpgid() error");
write(p1[1], &c, 1);
printf("parent's process group id is now %d\n", (int) getpgrp());
sleep(5);
}
}
parent's process group id is 5767174
child's process group id is 5767174
parent is performing setpgid() on pid 131084
parent's process group id is now 5767174
child is waiting for parent to complete task
child's process group id is now 131084