/*===============================================
* 文件名称:daemon.c
* 创 建 者:mf
* 创建日期:2023年04月17日
* 描 述:守护进程
================================================*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
int Create_Process(void)
{
/*1.创建子进程,父进程退出*/
pid_t pid=fork();
if(pid<0)
{
perror("fork");
return -1;
}
else if(pid>0)
{
exit(0);
}
/*2.在子进程中创建新会话*/
pid=setsid();
if(pid<0)
{
perror("setsid");
return -1;
}
/*3.改变当前目录为根目录*/
int ret=chdir("/mnt/hgfs/share");
//int ret=chdir("/tmp");
if(ret<0)
{
perror("chdir");
return -1;
}
/*4.重设文件权限掩码*/
umask(0);
/*5.关闭文件描述符*/
for(int i=0;i<getdtablesize();i++)
{
close(i);
}
return 0;
}
int main(int argc, char *argv[])
{
if(Create_Process()<0)
{
printf("create daemon failed\n");
return -1;
}
int line=0;
FILE *fp=fopen("888","a");
if(fp==NULL)
{
perror("fopen");
return -1;
}
while(1)
{
time_t t=time(NULL);
fprintf(fp,"%3d,%s",line++,ctime(&t));
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
守护进程的创建
最新推荐文章于 2024-09-11 22:21:57 发布