Sometimes it is necessary to create a new process such as MyServer in the C layer of Android, but we do not want to have multiple myserver at the same time.
This article describes a method that is equivalent to performing "PS MyServer" in the background, obtaining results, parsing, and invoking them in the main thread.
Querying whether a process named MyServer exists can be used like this:
Getmypid ();
The query failed to return 1, and no this process returns 0 if the process exists and returns the PID of the process.
The following is the code implementation.
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; } &nbSp; 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; &Nbsp;while (p!=null) { if (idx == n) { return strcpy (szret, p); } //kesyprintf (" [%d]%s\n ", n, p); p = strtok (NULL, Split); ++n; } return szret;} returned MYSERVER process id// query failed to return -1// No this process returned 0static 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; &nBsp; /* read each line from command output. */ while (Null != fgets (buffer, 1024, stream)) { // Analysis Results 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++; &nbsP;} /* Close the channel and get the status. */ status = pclose (Stream); kesyprintf ("ps exited with status %d\n", status); return gmypid; }}
Comments are welcome.
------------------by Jacksonke
The Android JNI layer ensures that only one implementation of a process