Linux C語言檢查程序是否存在
阿新 • • 發佈:2019-02-20
使用C語言根據程序名檢查程序是否存在,然後重啟程序
/* * COPYRIGHT NOTICE * Copyright (C) 2016 HuaHuan Electronics Corporation, Inc. All rights reserved * * Author :Kevin_fzs * File Name :/home/kevin/works/projects/MIPS53003/drivers/webRestart.c * Create Date :2016/08/04 01:11 * Last Modified :2016/08/04 01:11 * Description : */ #include <stdio.h> #include <stdlib.h> #include <string.h> int getRestartStatus() { char *name="/home/webserver/Rflag.txt"; FILE *fd; int ret=0; fd = fopen(name, "r"); if(NULL == fd) return 1; else return 0; } int main() { FILE *ptr = NULL; char cmd[128] = "ps -ef | grep appweb | grep -v grep | wc -l"; int status = 0; char buf[150]; int count; while(1) { status = getRestartStatus();<span style="white-space:pre"> </span>//根據標誌檔案來決定是否要檢查程序 if(status) { if((ptr = popen(cmd, "r"))==NULL) { printf("popen err\n"); continue; } memset(buf, 0, sizeof(buf)); if((fgets(buf, sizeof(buf),ptr))!= NULL)<span style="white-space:pre"> </span>//獲取程序和子程序的總數 { count = atoi(buf); if(count <= 0)<span style="white-space:pre"> </span>//當程序數小於等於0時,說明程序不存在 { system("/home/appweb_start.sh"); printf("restart appweb \n"); } } } usleep(200000); } }