Linux 下创建简单的守护进程(Daemon)

守护进程运行在背景,其父进程 pid=1(init/systemd). 创建守护进程的主要思路,就是 fork 一个子进程,然后父进程挂掉让子进程变为孤儿,最终孤儿被 pid=1 的进程领养。

Daemon 的创建步骤 (SysV)

1. Fork
fork off the parent process & let it terminate if forking was successful. -> Because the parent process has terminated, the child process now runs in the background.

2. Setsid
setsid - Create a new session. The calling process becomes the leader of the new session and the process group leader of the new process group. The process is now detached from its controlling terminal (CTTY).

3. Signal
Catch signals - Ignore and/or handle signals.

4. Fork again
fork again & let the parent process terminate to ensure that you get rid of the session leading process. (Only session leaders may get a TTY again.)

5. chdir
chdir - Change the working directory of the daemon.

6. umask
umask - Change the file mode mask according to the needs of the daemon.

7. Close FDs
close - Close all open file descriptors that may be inherited from the parent process.

继续阅读“Linux 下创建简单的守护进程(Daemon)”