Linux下用C语言判断程序是否已运行

通过程序名获得进程号,然后和当前程序进程号做对比。


int isRunning()
{
    int ret = 0;
    char sCurrPid[16] = {0};
    sprintf(sCurrPid, "%d\n", getpid());
    
    FILE *fstream=NULL;    
    char buff[1024] = {0};  

    // a.out为你的可执行程序名
    if(NULL==(fstream=popen("ps -aux | grep a.out | grep -v grep | awk '{print $2}'", "r")))    
    {   
        fprintf(stderr,"execute command failed: %s", strerror(errno));    
        return -1;    
    }   
    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;
}


另外一种兼容嵌入式设备。因为嵌入式设备可能没有awk命令,因此采用下面这个通用的方法。

char* getPidFromStr(const char *str)
{
    static char sPID[8] = {0};
    int tmp = 0;
    int pos1 = 0;
    int pos2 = 0;
    int i = 0;
    int j = 0;

    for (i=0; i='0' && str[i]<='9') ) {
            tmp = 1;
            pos1 = i;
        }
        if ( (tmp==1) && (str[i]<'0' || str[i]>'9') ) {
            pos2 = i;
            break;
        }
    }
    for (j=0,i=pos1; i


你可能感兴趣的:(linux)