如何获取祖父母/祖先进程 ID



如果可能的话,我想知道如何获取进程祖父级(或更远)的pid。

更具体地说,我希望进程在进程树中打印其深度。例如,从以下内容开始时:

int main() {
    int creator_id = (int) getpid();
    pid_t pid1 = fork();
    pid_t pid2 = fork();
    pid_t pid3 = fork();        
    //print depth in process tree of each process
    return 0;
}

根据我的理论,这棵树看起来像这样:

               0
              /| 
             / | 
            /  |  
           0   0   0
          /   |            
         0   0 0  
        /            
       0

所以我的第一个想法是以某种方式看看我必须多久上一次,直到我找到创作者的pid。

作为一点旁注:我还想知道是否可以自下而上地进行打印,这意味着最深层次的所有过程都将首先打印。

如何获取进程祖父级(或更远)的 PID。

这取决于您使用的操作系统,因为您在示例中使用 fork() 创建新进程,因此我想您使用的是一些类 Unix 系统。

如果您使用的是Linux并且知道进程的pid,则可以/proc/[pid]/stat从该文件的第四个字段中获取其父进程的pid,这是该文件的第四个字段。通过这个父子链,你可以找到一个进程的所有祖先。

按照 Duhem @Lee提示,我做了以下函数,返回当前进程的第 n 个祖先(第二个祖先是祖父级)。

/* Get the process ID of the calling process's nth ancestor. */
pid_t getapid(int n) {
  pid_t pid = getpid();
  while(n>0 && pid){ // process with pid 0 has no parent
    // strlen("/proc/") == 6
    // max [pid] for 64 bits is 4194304 then strlen("[pid]") < 7
    // strlen("/stat") == 5
    // then strlen("/proc/[pid]/stat") < 6 + 7 + 5
    char proc_stat_path[6+7+5+1];
    sprintf(proc_stat_path, "/proc/%d/stat", pid);
    // open "/proc/<pid>/stat"
    FILE *fh = fopen(proc_stat_path, "r");
    if (fh == NULL) {
      fprintf(stderr, "Failed opening %s: ", proc_stat_path);
      perror("");
      exit(1);
    }
    // seek to the last ')'
    int c;
    long pos = 0;
    while ((c = fgetc(fh)) != EOF) {
      if (c == ')')
        pos = ftell(fh);
    }
    fseek(fh, pos, SEEK_SET);
    // get parent 
    fscanf(fh, " %*c %d", &pid);
    // close "/proc/<pid>/stat"
    fclose(fh);
    // decrement n
    n--;
  }
  if(n>0)
    return -1;
  else
    return pid;
}

最新更新