linux判斷當前程序是否存在

#include <stdio.h>
#include <string.h>
int is_running(const char* prg)
{
    const char* pid_file = ".tmp_pid";
    const char* p = strrchr(prg,'/');
    if(p)
        p++;
    else
        p = prg;
    char cmd[128] = {0};
    sprintf(cmd,"pgrep %s >%s",p,pid_file);
    system(cmd);
    FILE* fp = fopen(pid_file,"r");
    if(fp == NULL){
        fprintf(stderr,"ERROR:can note open pid file:%s\n",pid_file);
        return -1;
    }    
    int pid = 0;
    char temp[256] = {0};
    while(fgets(temp,256,fp)){
        pid = atoi(temp);
        printf("pid1 = %d,pidcur = %d\n",pid,getpid());
        if(pid != getpid()){
            break;
        }
        else
            pid = 0;
    }
    fclose(fp);
    sprintf(cmd,"rm -f %s",pid_file);
    system(cmd);
    return pid;
}
int main(int argc,char** argv)
{
    int ret = is_running(argv[0]);
    if(ret == 0){
        printf("not running\n");
    }
    else {
        printf("is running\n");
    }
    sleep(10000);
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章