用c實現進程監控,如果某一進程退出則重啟

來源:互聯網
上載者:User

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/types.h>  
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>

//要監控的程式
#define P1
"hello1"
#define P2
"hello2"
#define P3
"hello3"
#define PATH
"."

/*****************************/
int is_run(char *name);
void killall_hello(void);
/*****************************/

//運行返回1,沒有運行返回0
int is_run(char *name)
{
int ret = -1;
char buf[256] = {'\0'};
snprintf(buf, sizeof(buf), "pidof %s >> /dev/null", name); 
ret = system(buf);
if(!WEXITSTATUS(ret)){ //#include <sys/wait.h>
//printf("%s is running!\n", name);
return 1;
}
else{
//printf("%s is not running!\n", name);

return 0;
}
}
void killall_hello(void)
{

char buf[128] = {'\0'};
snprintf(buf, sizeof(buf), "killall %s", P1);
system(buf);
snprintf(buf, sizeof(buf), "killall %s", P2);
system(buf);
snprintf(buf, sizeof(buf), "killall %s", P3);
system(buf);

}

int main(int argc, char **argv)
{
int p1_ret = -1;
int p2_ret = -1;
    int p3_ret = -1;
char buf[128];
bzero(buf, sizeof(buf));

while(1){

p1_ret = is_run(P1);
p2_ret = is_run(P2);
p3_ret = is_run(P3);

if (!(p1_ret && p2_ret && p3_ret))
{
killall_hello(); 
printf("rerun hello3\n");
snprintf(buf, sizeof(buf), "%s/%s &", PATH, P3);
system(buf);

//列印日誌資訊
system("date >> w.log");
if(!p1_ret){
snprintf(buf, sizeof(buf), "echo %s not run , killall , run %s >> w.log", P1, P3);
system(buf);
}
else if(!p2_ret){
snprintf(buf, sizeof(buf), "echo %s not run , killall , run %s >> w.log", P2, P3);
system(buf);
}
else if(!p3_ret){
snprintf(buf, sizeof(buf), "echo %s not run , killall , run %s >> w.log", P3, P3);
system(buf);
}
}
sleep(5);
}
exit(0);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.