如何将守护进程添加为开机自启

一、编写一个守护进程

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
int main(int argc,char *argv[])

{

	//1.创建孤儿进程
	pid_t pid=-1;
	int sum=0;
	int i=0;
	int fd;
	char *buf="this is a Daemonn\r\n";
	pid=fork();
	if(-1==pid)
	{
	
		printf("pid error\r\n");
		return -1;
	}
	else if(0<pid)
	{
	
		exit(0);
	}
	printf("fork success\r\n");
	//2,创建新会话层
	setsid();
	printf("creat ok %d\r\n",getpid());
	//3.改变文件目录
	chdir("/");
	//4.改变文件权限掩码
	umask(0);
	//5,改变文件描述符
	sum=getdtablesize();
	for(;i<sum;i++)
	{
	
		close(i);
	}
	//sleep(10);
	//5.守护进程执行函数
	while(1)
	{
	
        //注意,此处写入的地址必须为/tmp目录下,(写当前目录下不显示)“.log”为日志文件
		if((fd=open("/tmp/process1.log",O_CREAT|O_RDWR|O_APPEND,0600))<0)
		{
		
			printf("open file error\r\n");
			exit(1);
		}
		write(fd,buf,strlen(buf));
		close(fd);
		sleep(2);
	}
	exit(0);
	//return 0;
}

二、给/etc/rc.local 加权限(注意,方法有很多,这是其中一种,我试过可行的)

三,编辑rc.local

 

 路径是你自己的。

四,重新启动

五,查看文件是否自启成功

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值