Android JNI层确保只有一个进程的一个实现

有时须要在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

相关文章
相关标签/搜索