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;
    }
  • 相关阅读:
    java 基础知识
    winform判断一个事件是否已经绑定了事件处理函数
    优质文章
    优质博客
    缩略图的创建
    记录一次错误处理 (xml序列化和反序列化相关)
    文件同步软件
    博客园优质博主集锦
    不错的博文集锦
    cesiumjs
  • 原文地址:https://www.cnblogs.com/hzijone/p/15715738.html
Copyright © 2011-2022 走看看