linux Daemon的C语言应用 | KaiQ.Gu|KerwinKoo Blog

JerryXia 发表于 , 阅读 (0)

实现需求:

在终端机启动一个server,该Server在mips系统架构下不太稳定,在第一次启动和第一次连接Client时均会ACK退出。

实现一个守护进程,使该服务在此进程下启动,实现无论何种情况退出,均重启该server。

Update

目前项目的该模块功能已实现,这里记录下实现过程。

主函数实现:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <syslog.h>

int main(void) {
daemon(1, 0);
start_server();
return 0;
}

需要执行的部分放在函数start_server()中实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static void start_server() {
char server_cmd[64] = {0};
strcpy(server_cmd, SERVER_CMD);
for(;;)
{
int stat = 0;
char working_dir[64] = {0};

chdir(WORKING_DIR);
getcwd(working_dir, 64);
openlog("server-daemon.log", LOG_CONS | LOG_PID, 0);
syslog(LOG_USER | LOG_INFO, "working directory:%s\n", working_dir);
syslog(LOG_USER | LOG_INFO, "now start running server cmd:%s\n", server_cmd);

stat = system(server_cmd);

if(stat != 0) {
syslog(LOG_USER | LOG_INFO, "server quited with error code:%d\n", stat);
}
}
}

解释下上面这段函数的实现:

  • 两个宏需要定义: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到我指定的目录。