【Linux守护进程】一、进程组与会话

简介: 【Linux守护进程】一、进程组与会话

1. 进程组

进程组,也叫做作业。BSD于1980年前后向Unix中增加的一个新特性,代表一个或者多个进程的集合,每个进程都属于一个进程组。操作系统设计进程组的概念主要就是为了简化对多个进程的管理。

当父进程创建子进程的时候,默认父进程和子进程同属于同一个进程组,进程组的ID等于第一个进程的ID,也就是组长进程的ID。我们在使用kill杀死进程的时候,可以通过 kill -SIGKILL -进程组ID 来杀死整个进程组内的全部进程。组长进程可以创建一个进程组,只要进程组中有一个进程存在,那么这个进程组就存在,并且即使组长进程终止也不会影响进程组。进程组的生命周期时从进程组创建到进程组最后一个进程终止或转移到另一个进程组。而进程可以为自己或者子进程设置进程组ID。

2. 会话

创建会话的注意事项:

  • 调用进程不能是进程组组长(父进程不能创建会话),该进程变成新会话首进程session header;
  • 该进程成为一个新的进程组的组长进程,也就是说如果子进程创建了一个会话,那么子进程就脱离父进程的进程组,成为一个新进程的进程组组长;
  • 新会话丢弃原有的控制终端,该会话没有控制终端;
  • 该调用进程是组长进程,则出错返回,也就是说组长不能当会长;
  • 建立新会话时,先调用fork,父进程会终止,子进程调用setsid,也就是说,只有父进程终止了,子进程才能创建会话;

3. 总结

进程组:多个进程在同一个组,第一个进程默认是进程组组长。

会话:进程组的上一级,多个进程组对应一个会话。

创建会话的时候,不能使用进程组组长创建,必须使用组员创建。

创建会话主要包括创建子进程、结束父进程、子进程做会长三步。

4. setsid()和getsid()函数

4.1 setsid()函数

  • 包含头文件及函数原型
#include <unistd.h>
pid_t setsid(void);
  • 函数描述
    setsid() creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and has no controlling tty. The process group ID and session ID of the calling process are set to the PID of the calling process. The calling process will be the only process in this new process group and in this new session.
  • 函数参数
    void
  • 函数返回值
    On success, the (new) session ID of the calling process is returned. On error, (pid_t) -1 is returned, and errno is set to indicate the error.

4.2 getsid()函数

  • 包含头文件及函数原型
#include <unistd.h>
pid_t getsid(pid_t pid);
  • 函数描述
    getsid(0) returns the session ID of the calling process. getsid§ returns the session ID of the process with process ID p. (The session ID of a process is the process group ID of the session leader.)
  • 函数参数
    pid
  • 函数返回值
    On success, a session ID is returned. On error, (pid_t) -1 will be returned, and errno is set appropriately.
相关文章
|
2天前
|
存储 Linux Shell
Linux:进程等待 & 进程替换
Linux:进程等待 & 进程替换
29 9
|
2天前
|
存储 Linux C语言
Linux:进程创建 & 进程终止
Linux:进程创建 & 进程终止
24 6
|
17小时前
|
Linux 数据库
linux守护进程介绍 | Linux的热拔插UDEV机制
linux守护进程介绍 | Linux的热拔插UDEV机制
linux守护进程介绍 | Linux的热拔插UDEV机制
|
2天前
|
存储 安全 Linux
【Linux】详解进程通信中信号量的本质&&同步和互斥的概念&&临界资源和临界区的概念
【Linux】详解进程通信中信号量的本质&&同步和互斥的概念&&临界资源和临界区的概念
|
2天前
|
消息中间件 算法 Linux
【Linux】详解如何利用共享内存实现进程间通信
【Linux】详解如何利用共享内存实现进程间通信
|
2天前
|
Linux
【Linux】命名管道的创建方法&&基于命名管道的两个进程通信的实现
【Linux】命名管道的创建方法&&基于命名管道的两个进程通信的实现
|
2天前
|
Linux
【Linux】匿名管道实现简单进程池
【Linux】匿名管道实现简单进程池
|
2天前
|
Linux
【Linux】进程通信之匿名管道通信
【Linux】进程通信之匿名管道通信
|
2天前
|
Linux C++
【Linux】详解进程程序替换
【Linux】详解进程程序替换
|
2天前
|
存储 安全 Linux
Linux:进程地址空间
Linux:进程地址空间
21 10