一、实验目的
1、了解守护进程的生命周期及应用;
2、掌握编写守护进程的五个基本步骤。
二、实验内容
1、编写守护进程test,test每3秒钟打印一个数字,定向输出到trush.txt
2、编写并编译monitor.c,其功能为每5秒检测一次test是否正在运行;若未运行,则运行该程序。
3、先验证test是否能正常运行,需要执行test,然后用命令查看数字是否正常输出至trush.txt
4、然后执行kill命令终止进程,使用命令查看test此时并未运行
5、执行monitor,5秒钟后使用命令查看test此时已经运行
选做:将编写的守护进程设置为开机自启动。
三、源程序
test.c:
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid < 0)
{
//创建错误,退出
exit(1);
}
else if(pid > 0)
{
//父进程退出
exit(0);
}
//使子进程成为组长
setsid();
pid=fork();
if(pid > 0)
{
//再次退出,使进程不是组长,这样进程就不会打开控制终端
exit(0);
}
else if(pid < 0)
{
exit(1);
}
//关闭进程打开的文件句柄
for(i=0;i<NOFILE;i++)
close(i);
//改变目录
chdir("/home/user/test");
//重设文件创建的掩码
umask(0);
return;
}
void main()
{
FILE *fp;
int i=0;
init_daemon();
while(1)
{
i++;
sleep(3);
fp=fopen("/home/user/test/log/trush.txt","a");
if(fp>=0)
{
fprintf(fp,"%d\n",i);
fclose(fp);
}
}
return;
}
monitor.c:
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid<0)
{
//创建错误,退出
exit(1);
}
else if(pid>0)
{
//父进程退出
exit(0);
}
//使子进程成为组长
setsid();
pid=fork();
if(pid>0)
{
//再次退出,使进程不是组长,这样进程就不会打开控制终端
exit(0);
}
else if(pid<0)
{
exit(1);
}
//关闭进程打开的文件句柄
for(i=0;i<NOFILE;i++)
close(i);
//改变目录
chdir("/home/user/test");
//重设文件创建的掩码
umask(0);
return;
}
// 得到trush.txt文件大小
int file_size()
{
FILE *fp=fopen("/home/user/test/log/trush.txt","r");
if(!fp) return -1;
fseek(fp,0L,SEEK_END);
int size=ftell(fp);
fclose(fp);
return size;
}
void main()
{
FILE *fp;
time_t t;
init_daemon();
int size = file_size();
while(1)
{
sleep(5);
int size2 = file_size();
fp=fopen("/home/user/test/log/monitor.log","a");
if(fp>=0)
{
time(&t);
fprintf(fp,"size =%d,%s\n",size, asctime(localtime(&t)));
fclose(fp);
}
if(size2 > size)
{
size = size2;
}
else
{
system("/home/user/test/test.c.o");
}
}
return;
}
me.sh
/home/user/test/monitor.c.o
四、实验步骤、结果截图
(1)设置开机自启动
1. 编辑/etc/profile文件,命令如下:
sudo vim /etc/profile
2. 向文件中,添加如下内容:
(2)验证是否正确运行
1. 使用reboot命令重启计算机;
2. 验证monitor.c.o是否运行,使用如下命令:
3. 验证test.c.o是否运行,使用如下命令:
4. 使用kill命令终止进程:
可知,该进程已被结束。
5. monitor.c.o开机自启动,此时正在运行。等待5秒查看,test.c.o是否正确启动:
可知,test.c.o已被monitor.c.o再次启动。
6. 查看输出日志文件:
trush.txt内容:
monitor.log内容:
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务