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

在这里插入图片描述

欢迎关注博主 Mindtechnist 或加入【Linux C/C++/Python社区】一起探讨和分享Linux C/C++/Python/Shell编程、机器人技术、机器学习、机器视觉、嵌入式AI相关领域的知识和技术。



专栏传送门 :《Linux从小白到大神》 | 系统学习Linux开发、VIM/GCC/GDB/Make工具、Linux文件IO、进程管理、进程通信、多线程等,请关注专栏免费学习。


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.


在这里插入图片描述
在这里插入图片描述


  • 23
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 42
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 42
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mindtechnist

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值