1. 程式人生 > >Linux下用C語言判斷程式是否已執行

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<strlen(str); i++) {
        if ( (tmp==0) && (str[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<pos2; i++,j++) {
        sPID[j] = str[i];
    }
    return sPID;
}


int isRunning()
{
    int ret = 0;
    char sCurrPid[16] = {0};
    sprintf(sCurrPid, "%d", getpid());
    
    FILE *fstream=NULL;    
    char buff[1024] = {0};   
    if(NULL==(fstream=popen("ps -e -o pid,comm | grep a.out | grep -v PID | grep -v grep", "r")))    
    {   
        fprintf(stderr,"execute command failed: %s", strerror(errno));    
        return -1;    
    }   
    while(NULL!=fgets(buff, sizeof(buff), fstream)) {
        char *oldPID = getPidFromStr(buff);
        if ( strcmp(sCurrPid, oldPID) != 0 ) {
            printf("程式已經執行,PID=%s\n", oldPID);
            ret = 1;
        }
    }
    pclose(fstream);
    
    return ret;
}