1、守护进程的特点
1)、后台服务进程
2)、独立于控制终端
3)、周期性执行某任务
4)、不受用户登录注销影响(关机肯定影响
)
5)、一般采用以d结尾的名字(服务)
2、进程组
1)、进程的组长
组里边的第一个进程
进程组的id==进程组的组长的id
2)、进程组组长选用规则
进程中的第一个进程
3)、进程组的id的设定
进程组的id就是组长的进程id
3、会话
1)、创建一个会话注意事项:
不能是进程组组长
创建会话的进程称为进程组的组长
有些linux版本需要root执行此操作(ubuntu不需要)
创建出的新会话会丢弃原有的控制终端
一般步骤,先fork,父亲死,儿子执行创建会话操作
2)、获取进程所属的会话id
#include <unistd.h>
pid_t getsid(pid_t pid);
/*(
DESCRIPTION
getsid(0) returns the session ID of the calling process.
getsid(p) 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.)
RETURN VALUE
On success, a session ID is returned.
On error, (pid_t) -1 will be returned, and errno is set appropriately.
ERRORS
EPERM A process with process ID p exists,
but it is not in the same session as the calling process,
and the implementation considers this an error.
ESRCH No process with process ID p was found.
VERSIONS
This system call is available on Linux since version 2.0.
*/
3)、创建一个会话
#include <unistd.h>
pid_t setsid(void);
/*
DESCRIPTION
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 (i.e., its session ID is made
the same as its process ID).
The calling process also becomes the process group leader of a new process group in the session
(i.e., its process group ID is made the same as its process ID).
The calling process will be the only process in the new process group and in the new session.
The new session has no controlling terminal.
RETURN VALUE
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.
ERRORS
EPERM The process group ID of any process equals the PID of the calling process.
Thus, in particular, setsid() fails if the calling process is already a process group leader.
*/
对于进程、进程组、会话这篇文章解释的不错:
https://www.cnblogs.com/zengyiwen/p/5755191.html
4、创建守护进程
1)、fork子进程,父进程退出(必须)
2)、子进程创建新会话(必须)
setsid()
3)、改变当前工作目录chdir
有这么一种场景,要执行的程序在U盘里,在U盘的目录中启动程序,在启动过程中U盘被其他人拔掉了,这个时候就会出现问题,改变工作目录,就是怕出现类似情况,工作目录不见了,影响进程的执行,不是必须的,增强健壮性。
4)、重设文件掩码
子进程会继承父进程的掩码
增加程序操作的灵活性
umask(0)
5)、关闭文件描述符
主要目的是为了释放资源,可以不关闭
close(0);close(1);close(2);
守护进程和后台进程区别?
最重要的区别,也是最直观的区别,守护进程没有控制终端,而后台进程还有。
通过这样的方式启动firefox,
#firefox &
firefox现在在后台运行了,但是它等于守护进程吗?不!
因为它并没有脱离控制终端,不信?你试着吧启动firefox的终端关掉,看看firefox会不会跟着一起关闭。
1.后台的文件描述符也是继承于父进程,例如shell,所以它也可以在当前终端下显示输出数据。
但是daemon进程自己变成了进程组长,其文件描述符号和控制终端没有关联,是控制台无关的。
2.基本上任何一个程序都可以后台运行,但守护进程是具有特殊要求的程序,比如要脱离自己的父进程,成为自己的会话组长等,这些要在代码中显式地写出来
换句话说,守护进程肯定是后台进程,但反之不成立。守护进程顾名思义,主要用于一些长期运行,守护着自己的职责(监听端口,监听服务等)。我们的系统下就有很多守护进程。
3.守护进程成为了进程组长(或者会话组长),和控制终端失去了联系(其文件描述符也是继承于父进程的,但是在变成守护进程的同时stdin,stdout,stderr和控制台失去联系了)