QQ-Like-Server(1): 创建单例运行的守护进程

版权声明:本文由博主@杨领well发表在http://blog.csdn.net/yanglingwell,如果转载请注明出处。 https://blog.csdn.net/yanglingwell/article/details/88623754

QQ-Like-Server(1): 创建单例运行的守护进程

主要功能

  • daemon 函数创建守护进程:
  1. Close all open file descriptors except standard input, output, and error.
  2. Reset all signal handlers to their default.
  3. Sanitize(清洁) the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
  4. Call fork(), to create a background process.
  5. In the child, call setsid() to detach from any terminal and create an independent session.
  6. In the child, call fork() again, to ensure that the daemon can never re-acquire a terminal again.
  7. 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.
  8. In the daemon process, connect /dev/null to standard input, output, and error.
  9. In the daemon process, reset the umask to 0, so that the file modes passed to open(), mkdir() and such like directly control the access mode of the created files and directories.
  10. 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.
  11. In the daemon process, write the daemon PID (as returned by getpid()) to a PID file.
  12. In the daemon process, drop privileges, if possible and applicable.
  13. From the daemon process, notify the original process started that initialization is complete.
  14. Call exit() in the original process.
  • running_check: 文件锁实现单例进程

开源代码

参考文献

猜你喜欢

转载自blog.csdn.net/yanglingwell/article/details/88623754