标签:
有时需要在Android的C层中创建一个新的进程比如myServer,但是我们又不希望,同一时间有多个myServer存在。
本文介绍个方法,相当于在在后台执行"ps myServer",获取结果,进行分析,在主线程中调用。
查询一个名为myServer的进程是否存在可以这么使用:
getMyPid();
查询失败返回-1,没有这个进程返回0,如果进程存在就返回该进程的pid。
以下是代码实现。
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; } }
欢迎评论。
------------------ by jacksonke
标签:
原文地址:http://my.oschina.net/u/1445604/blog/495000