实现思路

  1. 获取 ps 命令输出并验证
  2. 读取 /proc 文件系统内容并验证 / 参考

参考例程

  • 程序一,检测某个服务是否运行,如果未运行则拉起。 ```c /**
  • FileName :Monitor.c *
  • Author : Tobiu *
  • Description: 守护进程; *
  • Date : Apr 18, 2018 **/

    include

    include

    include

    include

    include

    include

    include

    include

    include

    include

    include

    include

define MAXFILE 3

define USEPRINTF 1

/**

  • @Function : program_Running
  • @Description : 判断程序是否在运行
  • @Param :
  • service : 进程名
  • @return : exist : 1,no found value : 0 */ int program_Running(char service) { FILE fp; char cmd[128], buf[1024]; char *pLine;

    sprintf(cmd, “/bin/ps aux | /bin/grep %s | /bin/grep -v grep”, service); fp = popen(cmd, “r”); while( fgets(buf, sizeof(buf), fp) != NULL ) {

    1. pLine = strtok(buf, "\n");
    2. while( pLine )
    3. {
    4. if( strstr(pLine, service) )
    5. {
    6. pclose( fp );
    7. return 1;
    8. }
    9. pLine = strtok(NULL, "\n");
    10. }

    } pclose( fp ); return 0; }

int main(int argc, char* argv[]) { if( USEPRINTF ) printf(“homecentor\n”);

  1. pid_t pc, pid;
  2. pc = fork();
  3. if( pc < 0 )
  4. {
  5. if( USEPRINTF ) printf("error fork\n");
  6. exit(1);
  7. }
  8. else if( pc > 0 )
  9. {
  10. exit(0);
  11. }
  12. pid = setsid();
  13. if( pid < 0 )
  14. perror("setsid error");
  15. chdir("/");
  16. umask(0);
  17. int i;
  18. for(i=0; i<MAXFILE; i++)
  19. close(i);
  20. while( 1 )
  21. {
  22. /*监测homecentor*/
  23. if(!program_Running("homecenter"))
  24. {
  25. /* The program did not run */
  26. system("/usr/bin/killall -9 homecenter"); //杀进程
  27. system("/bin/taskset -c 0 /home/mycode/bin/homecenter &"); //重新启动
  28. }
  29. sleep(2);
  30. }
  31. return 0;

} ```

开源工具