守护进程简单模板

写一个简单的守护进程,原理就是调用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 $< ==> $@..." 
	$(CC) $(INC) $(CFLAGS) -c $< -o $@

ttdaemon: $(OBJECTS)
	@echo
	@echo "create archive $@...."
	$(CXX) -o $(BIN) $(OBJECTS) $(LIBS)

clean:
	rm -f $(BIN) 

后面会补充服务程序的添加方法。

猜你喜欢

转载自blog.csdn.net/andylauren/article/details/82728668
今日推荐