您的位置:首页 > 运维架构 > Linux

linux下监视进程,若进程关闭则自动重启

2013-04-28 02:17 726 查看
从事嵌入式行业已经3年,说来惭愧,我目前除了电路系统设计,PCB设计,while(1)系统程序设计就基本上不会什么了。面对外面世界的巨大压力,我觉得提升自我已经是一件刻不容缓的事情,于是在上周开始,我决定要接触嵌入式linux。

前天在群里遇到位仁兄提到他有个程序总是莫名其妙地自动关闭,他希望有段程序能够检测那个程序并在其关闭后自动将其重启。

我想了想准备试一试,于是有了下面几句代码,写的不好,希望遇到大侠指点一二!

#include
#include
#include
#include
#include
#include
#include

int main()
{
FILE *tmp;
int log;
int tmp2,i_id;
char *idname,*command;
int times;

if((log = open("./log.txt",O_CREAT | O_TRUNC | O_WRONLY,0666)) < 0)//输出重定向没弄好
{
perror("Can't Open log.txt");
exit(1);
}

while(1)
{
system("ps -ef|awk '$8 == \"gedit\"{print $2,\"a\"}'> pid.txt");//将gedit换成想要检测的进程名如/usr/lib64/firefox/firefox
printf("over!\n");
if((tmp = fopen("./pid.txt","r+"))== NULL)
{
perror("Open File Error:");
exit(1);
}

times = 0;
while(1)
{
i_id = 0;
tmp2 = fgetc(tmp);
while((tmp2 >= '0')&&(tmp2 <= '9'))
{
i_id *= 10;
i_id += tmp2 - '0';
tmp2 = fgetc(tmp);
}
if(i_id != 0)
{
times ++ ;
printf("program is running the PID is %d\n",i_id);
}
if(tmp2 != EOF)
continue;
else
break;
}
if(times == 0)
{
printf("program is done\n");
printf("now I am tring to restart it\n");
system("gedit");//这里的gedit也需要换掉!
}
sleep(5);
}
exit(1);
}


运行结果如下图所示

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: