zoukankan      html  css  js  c++  java
  • linux C 语言判断自身程序是否在运行

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <string.h>
    //TF处理
    #include <sys/vfs.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <fcntl.h>
    #include <dirent.h>
    #include <errno.h> //时间 #include <time.h> #include <sys/time.h> #include <iostream> #include <cstring> #include <iostream> #include <sstream>

     

    int isRunning(const char *procname)
    {
        int ret = 0;
        char sCurrPid[16] = {0};
        sprintf(sCurrPid, "%d\n", getpid());
        
        FILE *fstream=NULL;    
        char buff[1024] = {0};  
     
        snprintf(buff,1024,"ps | grep %s | grep -v grep | awk '{print $1}'",procname);
        if(NULL==(fstream=popen(buff, "r")))    
        {   
            fprintf(stderr,"execute command failed: %s", strerror(errno));    
            return -1;    
        }  
        memset(buff, 0, sizeof(buff));
        while(NULL!=fgets(buff, sizeof(buff), fstream)) {
            if (strlen(buff) > 0) {
                if (strcmp(buff, sCurrPid) !=0) {
                    //printf("******%s, %s****\n", buff, sCurrPid); 
                    ret = 1;
                    break;
                }
            }
        }
        pclose(fstream);
        return ret;
    }
    
    int main(int argc, char const *argv[])
    {
        if(1==isRunning(argv[0])) {
            printf("is running\n");
            return 0;
        }
        while(1) {
            sleep(1);
        }
        return 0;
    }
  • 相关阅读:
    ServletContext
    PS切图
    session实战案例
    Array Destruction
    Session详解
    No More Inversions 全网最详细 回文序列的逆序对
    Sum of Paths (DP、预处理)
    cookie详解
    web的状态管理
    简单最大流/最小割复习
  • 原文地址:https://www.cnblogs.com/hzijone/p/15715738.html
Copyright © 2011-2022 走看看