守护进程简单模板

写一个简单的守护进程,原理就是调用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) 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值