守护进程的简单应用--统计开机之后到现在所经历的时间
守护进程的简单应用--统计开机之后到现在所经历的时间
基于的原理是:守护进程从用户的登入,一直运行,直到用户的登出。
守护进程的创建步骤:
1.创建子进程,父进程退出 fork() exit()
2.在子进程中创建新的会话 setsid()
3.将工作目录改为根目录 chdir("/")
4.更改掩码 umask(0) //一般设为0,默认为022,也就是取消组内,和其他组的写权限
5.关闭文件描述符 一个进程一般有1024个文件描述符,可用 fnum = getdtablesize()得到 //get description table size
程序源代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t pid;
int fd;
char flag[] = "\n\t--This is a time from power on the computer to now--\n\n";
char buf[19] = {'D','D',' ',':',' ','H','H',' ',':',' ','M','M',' ',':',' ','S','S','\n','\0'};
char time[19] = {'0','0',' ',':',' ','0','0',' ',':',' ','0','0',' ',':',' ','0','0','\n','\0'};
int fnmax;
pid = fork();
if(pid < 0)
{
perror(" fail to fork\n");
return -1;
}
if(pid == 0)
{
if(setsid() < 0)
{
perror(" fail to setsid\n");
return -1;
}
chdir("/");
umask(0);
fnmax = getdtablesize();
for(fd = 0; fd < fnmax; fd++)
{
close(fd);
}
while(1)
{
fd = open("/home/linux/since_pcon_time.log", O_CREAT | O_WRONLY, 0666);
time[16] = ((++time[16]) - '0') % 10 + '0';
if(time[16] == '0')
{
time[15] = (++(time[15]) - '0') % 6 + '0';
if(time[15] == '0')
{
time[11] = (++(time[11]) - '0') % 10 + '0';
if(time[11] == '0')
{
time[10] = (++(time[10]) - '0') % 6 + '0';
if(time[10] == '0')
{
if(time[5] < '2')
{
time[6] = (++(time[6]) - '0') % 10 + '0';
if(time[6] == '0')
{
time[5] = (++(time[5]) - '0') % 3 + '0';
if(time[5] == '0')
{
time[1] = (++(time[1]) - '0') % 10 + '0';
if(time[1] == '0')
{
time[0] = (++(time[0]) - '0') % 10 + '0';
}
}
}
}
else
{
time[6] = (++(time[6]) - '0') % 4 + '0';
if(time[6] == '0')
{
time[5] = (++(time[5]) - '0') % 3 + '0';
if(time[5] == '0')
{
time[1] = (++(time[1]) - '0') % 10 + '0';
if(time[1] == '0')
{
time[0] = (++(time[0]) - '0') % 10 + '0';
}
}
}
}
}
}
}
}
write(fd, flag, 56);
write(fd, buf, 18);
write(fd, time, 18);
close(fd);
printf("time = %s\n",time);
sleep(1);
}
}
if(pid > 0)
{
exit(0);
}
return 0;
}
程序执行结果
1.ps -ajx
PPID PID PGID SID TTY STAT
可以看出她既是进程组组长,还是会话组组长,完全独立与任何终端。
2.vi since_pcon_time.log
可以看出来,程序已经辛辛苦苦的跑了39分07秒了。。。
设置开机自启动方法
单击右上角的齿轮,在菜单项中选择startup....选项,add可执行文件即可。
(全篇完)
By DestinyX
评论