第九章 进程关系:
#include <unistd.h>
pid_t getpgrp(void);
get pgid (>0)
#include <unistd.h>
pid_t getpgid(pid_t pid);
getpgid(0) same as getpgid(getpid()) same as getpgrp()
if error return -1
#include <unistd.h>
int setpgid(pid_t pid, pid_t pgid);
setpgid(0, pgid) same as setpgid(getpid(), pgid)
setpgid(pid, 0) same as setpgid(pid, pid)
if error return -1
#include <unistd.h>
pid_t setsid(void);
if current process is not a process group leader,
will create a new session
else failed
if success return pgid, else return -1
#include <unistd.h>
pid_t getsid(pid_t pid);
getsid(0) same as getsid(getpid())
#include <unistd.h>
pid_t tcgetpgrp(int filedes);
if error return -1
int tcsetpgrp(int filedes, pid_t pgid);
if success return 0, else return -1
#include <termios.h>
pid_t tcgetsid(int filedes);
if error return -1
示例:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void
sig_hup(int signo)
{
printf("SIGHUP received, pid = %d\n", getpid());
}
void
pr_ids(const char * name)
{
printf("%s: pid = %d, ppid = %d, pgrp = %d, tpgrp = %d\n",
name, getpid(), getppid(), getpgrp(), tcgetpgrp(STDIN_FILENO));
fflush(stdout);
}
int
main(void)
{
char c;
pid_t pid;
pr_ids("parent");
if ((pid = fork()) < 0) {
printf("fork error\n");
exit(-1);
}
else if (pid > 0) {
sleep(5);
exit(0);
}
else {
pr_ids("child");
signal(SIGHUP, sig_hup);
kill(getpid(), SIGTSTP);
pr_ids("child");
if (read(STDIN_FILENO, &c, 1) != 1) {
printf("read error from controlling TTY, errno = %d\n", errno);
}
exit(0);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void
pr_ids(const char * info)
{
printf("\n%s: pid = %d, ppid = %d, pgrp = %d, sid = %d, tpgrp = %d\n",
info, getpid(), getppid(), getpgrp(), getsid(0),
tcgetpgrp(STDIN_FILENO));
fflush(stdout);
}
int
main(void)
{
pid_t pid;
int c;
if ((pid = fork()) < 0) {
printf("fork error\n");
exit(-1);
}
else if (pid > 0) {
sleep(1);
printf("parent exit\n");
exit(0);
}
else {
pr_ids("before");
sleep(2);
setsid();
pr_ids("after");
exit(0);
}
}