守护进程
进程运行在后台,在Linux启动时执行,系统关闭后结束。如tftp、nfs等都是守护进程。
守护进程特点
1、始终在后台运行,后台进程(只能向终端输出,不能向终端输入);
2、独立于任何终端(与交互进程最本质区别);
3、周期性的执行某种任务或等待处理特定事件。
步骤
1、创建子进程,父进程退出;
pit_t pit = fork();//创建进程
if(pit < 0)
{
perror("fork");
return -1;
}
if(pit > 0)//父进程
exit(0);//关闭父进程
else//子进程
{}
2、在子进程中创建新会话;
pid_t setsid(void);
3、改变当前目录为根目录(防止当前目录被删除);
int chdir(const char *path);
4、重设文件权限掩码(mode & ~umask);
mode_t umask(mode_t mask);
5、关闭文件描述符(父进程拷贝来的);
int close(int fd);
6、向文件中写入时间;
time_t time(time_t *tloc);
struct tm *localtime(const time_t *timep);
demo.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
pid_t pit = fork();
if(pit < 0)
{
perror("fprk");
return -1;
}
else if(pit > 0)// 父进程
exit(0); //关闭父进程
else
{
//创建新会话
if(-1 == setsid())
{
perror("setsid");
exit(-1);
}
//修改工作目录为根目录
if(-1 == chdir("/"))
{
perror("chdir");
exit(-1);
}
//修改文件权限掩码
umask(0);
// 关闭文件描述符
int fd_num = getdtablesize();
int i = 0;
for(i=0;i<fd_num;i++)
close(i);
//向文件中写入时间
time_t tm;
struct tm *tp;
FILE *fp = fopen("time.txt","a");
if(NULL == fp)
{
perror("fopen");
exit(-1);
}
while(1)
{
time(&tm);
tp = localtime(&tm);
fprintf(fp,"%4d-%02d-%02d %02d:%02d:%02d\n",tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday,tp->tm_hour,tp->tm_min,tp->tm_sec);
fflush(fp);
sleep(1);
}
fclose(fp);
exit(0);
}
}
编译结果
ww@ubuntu:~/day3$ sudo ./a.out
ww@ubuntu:~/day3$ ls /
bin dev lib mnt root snap sys tmp
boot etc opt run srv usr cdrom home media time.txt var
ww@ubuntu:~/day3$ cat /time.txt
2022-10-20 05:40:44
2022-10-20 05:40:45
2022-10-20 05:40:46
2022-10-20 05:40:47
2022-10-20 05:40:48