一、实验目的
二、实验内容
1、编写守护进程test,test每5秒钟打印一个数字,定向输出到trush.txt。
2、编写并编译monitor.c,其功能为每5秒检测一次test是否正在运行;若未运行,则运行该程序。
3、先验证test是否能正常运行,需要执行test,然后用命令查看数字是否正常输出至trush.txt。
4、然后执行kill命令终止进程,使用命令查看test此时并未运行。
5、执行monitor,5秒钟后使用命令查看test此时已经运行。
选做部分:将编写的守护进程设置为开机自启动。
三、实验源程序及结果截图
test.sh
i=1 while (true) do echo $i>>/home/zhang/experiment/experiment_3/trush.txt i=$(($i+1)) sleep 1 done
讯享网
monitor.c
讯享网#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <syslog.h> #include <sys/stat.h> pid_t process() {
pid_t pr; pr = fork(); if (pr == 0) {
system("/home/zhang/experiment/experiment_3/test.sh"); // 按文件名查找文件 } return pr; } int main() {
pid_t pc; // 守护进程 pid_t pr; // 临时变量: 返回值 pid_t pd; // 被守护进程 pc = fork(); if (pc < 0) {
printf("Error fork!\n"); } else if (pc > 0) {
// 父进程 sleep(2); exit(0); } else if (pc == 0) {
// 子进程 setsid(); chdir("/"); umask(0); for (int i = 0; i < getdtablesize(); ++i) {
close(i); } pd = process(); do {
do {
pr = waitpid(pd, NULL, WNOHANG); if (!pr) {
sleep(5); } } while (pr == 0); pd = process(); } while (1); exit(0); } }
设置守护进程开机自启动
添加内容
/home/zhang/experiment/experiment_3/monitor
sudo vim /etc/profile
在文件末尾添加
讯享网sh /home/zhang/experiment/experiment_3/me.sh
四、实验截图
编译monitor

讯享网

后台运行test.sh,并把生成的值写入trush.txt

杀死test.sh并查看确认被杀死

运行monitor.c,并检索sh进程

杀死进程test

一会儿后test再度被启动

杀死monitor

再杀死test

此时的test不会在被激活

五、实验问题总结
/etc/profile:这个文件是每个用户登录时都会运行的环境变量设置,所以将monitor的启动脚本写在这里可以开机自启动monitor,从而启动test.sh
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/135597.html