當前位置:編程學習大全網 - 源碼下載 - 寫壹個linux下寫個關於c語言的雙守護進程,就是監視壹個進程,當其死掉,馬上將其重啟

寫壹個linux下寫個關於c語言的雙守護進程,就是監視壹個進程,當其死掉,馬上將其重啟

可以分三步來做:

做兩個簡單的守護進程,並能正常運行

監控進程是否在運行

啟動進程

綜合起來就可以了,代碼如下:

被監控進程thisisatest.c(來自blogs.com/ringwang/p/3528093.html):

#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("/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=0;i<NOFILE;i++)

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 ? -- 查看日誌

  • 上一篇:聊天加密的軟件有哪些可以隱私聊天的軟件推薦
  • 下一篇:壹種更優雅的Flutter Dialog解決方案
  • copyright 2024編程學習大全網