linux Daemon的C语言应用 | KaiQ.Gu|KerwinKoo Blog
实现需求:
在终端机启动一个server,该Server在mips系统架构下不太稳定,在第一次启动和第一次连接Client时均会ACK退出。
实现一个守护进程,使该服务在此进程下启动,实现无论何种情况退出,均重启该server。
Update
目前项目的该模块功能已实现,这里记录下实现过程。
主函数实现:
1 | #include <stdio.h> |
需要执行的部分放在函数start_server()中实现。
1 | static void start_server() { |
解释下上面这段函数的实现:
- 两个宏需要定义:
SERVER_CMD指定程序执行的命令;WORKING_DIR指定该server运行时的环境路径。 - for(;;)循环中,无论因何种原因server退出,均再次启动。启动后,需要在system()函数处执行时阻塞。
- 为实现上面的执行时阻塞,需要保证server_cmd本身不包含daemon。即nodaemon server。
daemon函数
daemon - run in the background #include <unistd.h> int daemon(int nochdir, int noclose); If nochdir is zero, daemon() changes the calling process's current working directory to the root directory ("/");otherwise, the current working directory is left unchanged. If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.将nochdir 设为1是因为我不需要在根目录中执行,而是在server实现体中自己chdir到我指定的目录。