[root@mylinux ap]# vi 9.4setsid.c
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <fcntl.h>
5
6 int
7 main(void)
8 {
9 pid_t pid;
10
/* 打印父进程的进程ID,及进程组ID */
11 printf("father's pid is %d,pgid is %d\n", getpid(), getpgid(0));
12 if ((pid = fork()) < 0) { /* fork子进程 */
13 printf("fork error\n");
14 exit(1);
15 }
16 else if (pid == 0) { /* 子进程 */
17 printf("before set,child's pid is %d,pgid is %d\n", getpid(), getpgid(0)); //打印子进程的进程ID与进程组ID
18 if (setsid() < -1) { //创建新会话
19 printf("setsid error\n");
20 exit(1);
21 }
22 printf("sid is %d\n", getsid(0)); //查看会话ID
23 if (open("/dev/tty", O_RDWR) < 0) { //验证子进程是否具有控制终端
24 printf("open error\n");
25 exit(1);
26 }
27 exit(0);
28 }
29 if (open("/dev/tty", O_RDWR) < 0) { //难父进程是否具有控制终端
30 printf("open error\n");
31 exit(1);
32 }
33 else
34 printf("father open ok\n");
35 exit(0);
36 }
[root@mylinux ap]# ./a.out
father's pid is 26252,pgid is 26252
before set,child's pid is 26253,pgid is 26252
sid is 26253 //创建新会话成功,会话的首进程的进程组ID为子进ID
open error //子进程不具有控制终端
father open ok //父进程具有控制终端