有時須要在Android的C層中建立一個新的進程好比myServer,可是咱們又不但願,同一時間有多個myServer存在。spa
本文介紹個方法,至關於在在後臺執行"ps myServer",獲取結果,進行分析,在主線程中調用。線程
查詢一個名爲myServer的進程是否存在能夠這麼使用:code
getMyPid();orm
查詢失敗返回-1,沒有這個進程返回0,若是進程存在就返回該進程的pid。進程
如下是代碼實現。get
int pidIndex(const char* szData) { char buf[256]; strcpy(buf, szData); kesyPrintf("%s\n",buf); int idx = -1; const char * split = " "; char * p = strtok (buf,split); while(p!=NULL) { ++idx; kesyPrintf("[%d]%s\n",idx, p); if (strcmp(p, "PID") == 0){ return idx; } p = strtok(NULL,split); } return -1; } static const char* getSubStr(const char* szData, int idx, char* szRet) { if (idx < 0){ return szRet; } char buf[1024]; strncpy(buf, szData, sizeof(buf)); buf[sizeof(buf) - 1] = '0'; const char * split = " "; char * p = strtok (buf,split); int n =0; while(p!=NULL) { if (idx == n){ return strcpy(szRet, p); } //kesyPrintf("[%d]%s\n",n, p); p = strtok(NULL,split); ++n; } return szRet; } // 返回myServer的進程id // 查詢失敗返回-1 // 沒有這個進程返回0 static pid_t getMyPid() { FILE* stream; /* Opening a read-only channel to ls command. */ char tmpCmd[256]; sprintf(tmpCmd, "ps %s", "myServer"); stream = popen(tmpCmd, "r"); if (NULL == stream) { kesyPrintf("Unable to execute the command."); return -1; } else { char buffer[1024]; int status; int line = 0; int pidIdx = -1; /* Read each line from command output. */ while (NULL != fgets(buffer, 1024, stream)) { // 分析結果 kesyPrintf("read: %s\n", buffer); if (0 == line){ pidIdx = pidIndex(buffer); } else{ char szPid[64]; char szRet[64]; strcpy(szPid, getSubStr(buffer, pidIdx, szRet)); gMyPid = atoi(szPid); } line++; } /* Close the channel and get the status. */ status = pclose(stream); kesyPrintf("ps exited with status %d\n", status); return gMyPid; } }
歡迎評論。it
------------------ by jacksonkeclass