1. 程式人生 > >守護程序簡單模板

守護程序簡單模板

寫一個簡單的守護程序,原理就是呼叫glibc庫函式daemon,建立daemon守護程序。

然後如果守護的程序異常終止測5s後重啟,暫時沒有實現看門狗功能,後面會補充上。

daemon.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include<sys/wait.h>

/**
 * @Brief  write the pid into the szPidFile
 *
 * @Param szPidFile name of pid file
 */

int main(int argc, char *argv[])
{
	pid_t pid;

	if (daemon(0, 0)) {//呼叫glibc庫函式daemon,建立daemon守護程序
		perror("daemon");
		return -1;
	}
	while(1) {
		if ( (pid = fork()) == 0 ) {/* 子程序執行此命令 */
			execlp( "/home/rt/inifile/bin/test", "test", NULL );
			/* 如果exec函式返回,表明沒有正常執行命令,列印錯誤資訊*/
			printf("execlp out\n");
			return( -1 );
		} else {
			wait ( &pid );
			printf("wait out\n");
		}
		sleep(5);
	}
	return 0;
}

makefile

INC= 
LIBS= 

CFLAGS= -g -Wall -Wno-deprecated

BIN= ttdaemon
OBJECTS= daemon.o
all: $(BIN)
 
%.o: %.c 
	@echo 
	@echo "Compiling $< ==> [email protected]" 
	$(CC) $(INC) $(CFLAGS) -c $< -o [email protected]

ttdaemon: $(OBJECTS)
	@echo
	@echo "create archive [email protected]
" $(CXX) -o $(BIN) $(OBJECTS) $(LIBS) clean: rm -f $(BIN)

後面會補充看門狗功能。