码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-08-20 13:26:11      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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


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

标签:

原文地址:http://my.oschina.net/u/1445604/blog/495000

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!