
可以分三步来做:
做两个简单的守护进程,并能正常运行
监控进程是否在运行
启动进程
综合起来就可以了,代码如下:
被监控进程thisisatest.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=0i<NOFILEi++)
close(i)
chdir("/root/test") //改变目录
umask(0)//重设文件创建的掩码
return
}
void main()
{
FILE *fp
time_t t
init_daemon()
while(1)
{
sleep(60)//等待一分钟再写入
fp=fopen("testfork2.log","a")
if(fp>=0)
{
time(&t)
fprintf(fp,"current time is:%s\n",asctime(localtime(&t))) //转换为本地时间输出
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>
#include<sys/wait.h>
#include<fcntl.h>
#include<limits.h>
#define BUFSZ 150
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=0i<NOFILEi++)
close(i)
chdir("/root/test") //改变目录
umask(0)//重设文件创建的掩码
return
}
void err_quit(char *msg)
{
perror(msg)
exit(EXIT_FAILURE)
}
// 判断程序是否在运行
int does_service_work()
{
FILE* fp
int count
char buf[BUFSZ]
char command[150]
sprintf(command, "ps -ef | grep thisisatest | grep -v grep | wc -l" )
if((fp = popen(command,"r")) == NULL)
err_quit("popen")
if( (fgets(buf,BUFSZ,fp))!= NULL )
{
count = atoi(buf)
}
pclose(fp)
return count
// exit(EXIT_SUCCESS)
}
void main()
{
FILE *fp
time_t t
int count
init_daemon()
while(1)
{
sleep(10)//等待一分钟再写入
fp=fopen("testfork3.log","a")
if(fp>=0)
{
count = does_service_work()
time(&t)
if(count>0)
fprintf(fp,"current time is:%s and the process exists, the count is %d\n",asctime(localtime(&t)), count) //转换为本地时间输出
else
{
fprintf(fp,"current time is:%s and the process does not exist, restart it!\n",asctime(localtime(&t))) //转换为本地时间输出
system("/home/user/daemon/thisisatest")//启动服务
}
fclose(fp)
}
}
return
}
具体CMD命令:
cc thisisatest.c -o thisisatest
./thisisatest
cc monitor.c -o monitor
./monitor
tail -f testfork3.log -- 查看日志
根据调用需求,可以分为两种:
一、仅执行系统命令,不需要该命令的打印结果。
这种情况可以用system函数。形式为
system(cmd)
其中cmd为char*类型的字符串,包含要执行的命令,命令的执行结果会输出到标准输出。
比如
system("mkdir test")这个执行,会在当前文件夹下创建test文件夹。
二、需要命令执行的打印。
虽然同样可以使用system并重定向到文件,然后打开文件读取,最终删除文件。但这样做比较繁琐,更好的做法是使用popen。
FILE *fp = popen(cmd)
执行cmd中的命令,然后可以以C文件 *** 作方式,读取命令的输出结果。比如:
if((fp=popen("pwd","r"))==NULL)//执行获取当前目录的系统命令pwd。{
printf("执行失败\n")//fp为NULL表示命令执行失败。
}
else
{
char s[100]
while(fgets(s, 100, fp))//获取文件内容。
printf("%s", s)//输出结果。
pclose(fp)//关闭。
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)