星期一, 11月 25, 2013

Get ProcessId by Process Name on FreeBSD/Mac OS X

因為某原因,我必須在FreeBSD上寫個daemon去監控另一個process,也就是俗稱的Watch Dog,貪圖開發方便,就用OS X上的XCode當作開發工具。

原本在FreeBSD上有kvm_getprocs,但是OS X上並沒有(另外我不知道會不會造成只看得到user space process),所以我就改找sysctl
int getProcessIdByName(char *processname)
{
 struct kinfo_proc *procs = NULL, *newprocs;
 char  thiscmd   [MAXCOMLEN + 1];
 pid_t  thispid;
 int  mib        [4];
 size_t  miblen;
 int  i         , st, nprocs;
 size_t  size;

 int  processid = 0;
 size = 0;
 mib[0] = CTL_KERN;
 mib[1] = KERN_PROC;
 mib[2] = KERN_PROC_ALL;
 mib[3] = 0;
 miblen = 3;

 st = sysctl(mib, (u_int) miblen, NULL, &size, NULL, 0);
 do {
  size += size / 10;
  newprocs = realloc(procs, size);
  if (newprocs == 0) {
   if (procs)
    free(procs);
  }
  procs = newprocs;
  st = sysctl(mib, (u_int) miblen, procs, &size, NULL, 0);
 } while (st == -1 && errno == ENOMEM);

 nprocs = (int)size / sizeof(struct kinfo_proc);

 for (i = 0; i < nprocs; i++) {
  thispid = procs[i].ki_pid;
  strncpy(thiscmd, procs[i].ki_comm, MAXCOMLEN);
  thiscmd[MAXCOMLEN] = '\0';
  if (strcmp(thiscmd, processname) == 0) {
   processid = thispid;
  }
 }
 free(procs);
 return processid;
}

沒有留言: