会话
会话:是一个或多个进程组的集合。
创建一个会话需要注意以下6点注意事项:
- 调用进程不能是进程组组长,该进程变成新会话首进程(session header)
- 该进程成为一个新进程组的组长进程。
- 需要root权限(ubuntu不需要)
- 新会话丢弃原有的终端控制,该会话没有控制终端
- 该调用进程是组长进程,则出错返回
- 建立会话时, 先调用fork,父进程终止,子进程调用setsid
1. setsid函数:创建一个会话,并以自己的ID设置进程组ID,同时也是新会话ID
pid_t Setsid(void);
分析:调用了setsid函数的进程,既是新的会长,也是新的组长。
2. getsid函数:获取进程所属会话ID
pid_t getsid(pid_t pid);
分析:
- pid为0,返回调用进程的会话首进程的进程组ID
- 如果pid不属于调用者所在的会话,那么调用进程就不能得到该会话首进程的进程组ID
3. 举例说明
sunbin@sunbin:~$ cat | cat & [1] 53903 sunbin@sunbin:~$ cat | cat | cat
结果分析:
ppid pid pgid sid 41184 53884 41270 41270 ? -1 Rl 1000 0:00 /usr/lib/gnome-ter 53884 53889 53889 53889 pts/4 53904 Ss 1000 0:00 bash 53889 53902 53902 53889 pts/4 53904 T 1000 0:00 cat 53889 53903 53902 53889 pts/4 53904 T 1000 0:00 cat 53889 53904 53904 53889 pts/4 53904 S+ 1000 0:00 cat 53889 53905 53904 53889 pts/4 53904 S+ 1000 0:00 cat 53889 53906 53904 53889 pts/4 53904 S+ 1000 0:00 cat 53884 53907 53907 53907 pts/18 53918 Ss 1000 0:00 bash 53907 53918 53918 53907 pts/18 53918 R+ 1000 0:00 ps ajx
程序清单
1. 测试代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 5 int main() 6 { 7 pid_t pid; 8 if((pid = fork()) < 0) 9 { 10 perror("fork"); 11 exit(1); 12 } 13 else if(pid == 0) 14 { 15 printf("child process PID is %d ", getpid()); 16 printf("Group process of child is %d ", getpgid(0)); 17 printf("Session ID of child is %d ", getsid(0)); 18 19 sleep(10); 20 setsid(); //子进程非组长进程,故其成为新会话首进程,且成为组长进程,该进程组id即为会话进程id 21 22 printf("change "); 23 24 printf("child process PID is %d ", getpid()); 25 printf("Group process of child is %d ", getpgid(0)); 26 printf("Session ID of child is %d ", getsid(0)); 27 28 sleep(20); 29 exit(0); 30 } 31 printf("parent process PID is %d ", getpid()); 32 return 0; 33 }
输出结果: