守护进程
1 作用
- 防止某些不可预期的意外导致主进程异常结束后,系统完全宕机没有任何反应
2 原理
- 守护进程(Daemon)是一种运行在后台的一种特殊的进程,它独立于控制终端并且周期性的执行某种任务或等待处理某些发生的事件。
- 被执行的时候开始运转,直到整个系统关闭才退出。
- 脱离于终端并且在后台运行,并且它脱离终端的目的是为了避免进程在运行的过程中的信息在任何终端中显示并且进程也不会被任何终端所产生的终端信息所打断
- 守护进程必须在启动伊始,就去除掉一些系统相关的限制
3 不同系统平台上的实现
linux
setsid()
- setsid()之后没有脱离(是不是父进程不死,就无法独立)
- 父进程被关闭后,子进程成为syatemd的子进程
//
// ├─gnome-terminal-─┬─bash───telnet
// │ ├─13*[bash]
// │ ├─bash───myproj───sayhello
[sxy@DESKTOP-SXY build]$ ps -ef | grep sayhello
sxy 5649 1 0 14:36 ? 00:00:00 ./myproj /home/sxy/Github/cpp/daemom/build/build/sayhello
sxy 5827 5649 0 14:38 ? 00:00:00 /home/sxy/Github/cpp/daemom/build/build/sayhello
sxy 5859 5008 0 14:38 pts/1 00:00:00 grep --color=auto sayhello
[sxy@DESKTOP-SXY build]$ killall sayhello
[sxy@DESKTOP-SXY build]$ ps -ef | grep sayhello
sxy 5649 1 0 14:36 ? 00:00:00 ./myproj /home/sxy/Github/cpp/daemom/build/build/sayhello
sxy 5873 5649 0 14:38 ? 00:00:00 /home/sxy/Github/cpp/daemom/build/build/sayhello
sxy 5882 5008 0 14:38 pts/1 00:00:00 grep --color=auto sayhello
4 参考文档
- https://blog.csdn.net/LEON1741/article/details/78021871
- linux程序启动时创建pid文件https://www.cnblogs.com/yanhai307/p/10511816.html
5 其他