版权声明:本文由博主@杨领well发表在http://blog.csdn.net/yanglingwell,如果转载请注明出处。 https://blog.csdn.net/yanglingwell/article/details/88623754
QQ-Like-Server(1): 创建单例运行的守护进程
主要功能
- daemon 函数创建守护进程:
- Close all open file descriptors except standard input, output, and error.
- Reset all signal handlers to their default.
- Sanitize(清洁) the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
- Call
fork()
, to create a background process. - In the child, call
setsid()
to detach from any terminal and create an independent session. - In the child, call
fork()
again, to ensure that the daemon can never re-acquire a terminal again. - Call
exit()
in the first child, so that only the second child (the actual daemon process) stays around. This ensures that the daemon process is re-parented to init/PID 1, as all daemons should be. - In the daemon process, connect /dev/null to standard input, output, and error.
- In the daemon process, reset the
umask
to 0, so that the file modes passed toopen()
,mkdir()
and such like directly control the access mode of the created files and directories. - In the daemon process, change the current directory to the rootdirectory (
/
), in order to avoid that the daemon involuntarily blocks mount points from being unmounted. - In the daemon process, write the daemon PID (as returned by
getpid()
) to a PID file. - In the daemon process, drop privileges, if possible and applicable.
- From the daemon process, notify the original process started that initialization is complete.
- Call
exit()
in the original process.
- running_check: 文件锁实现单例进程