首页 > 解决方案 > 如何通过系统调用获取孩子的 PID?

问题描述

我编译并安装了一个新版本的内核,现在我必须让新内核支持两个新的原语,我在下面解释更多

我有这个文件,mysystemcalls-test.c ,我在其中获取进程并在for迭代中进行分叉。这是我的测试文件。

//mysyscalls-test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <mysyscalls.h>

#define NCHILDREN 10

int main()
{

  int pids[NCHILDREN], i;
  int original_parent = getpid();

  printf ("before fork: current number of children: %ld\n", getnchildren(1));

  for (i=0; i<NCHILDREN; i++) {
    pids[i] = fork();

    if (pids[i] == 0) {
    while (getppid() == original_parent);
      exit(0);
    }
  }
printf("after fork: current number of children: %ld\n", getnchildren(1));

for(i=0; i<NCHILDREN; i++)
  printf("pids[%d]:%d\tgetcpid(%d,1):%ld\n" ,i,pids[i],i,getcpid(i,1));

return 0;
}

真正的问题在于第二个文件mysyscalls.h我无法正确调用子进程。

//mysyscalls.h

long getnchildren (int debug){
  int children;
  children = pids[i];
  return children;
}


long getcpid (int order, int debug){
  int childrenid;
  childrenid = getpid();
  return childrenid;
}

我不知道如何在 mysyscalls.h 文件中调用这些 pid。我搜索并测试了我在这里找到的一些代码,但我对我的问题没有确切的答案。我写了那个代码但没有工作,它返回相同的 pid。

假设long getnchildren返回调用进程在调用原语时所拥有的子进程的数量。

long getcpid返回调用进程的子进程的 pid,在其子进程列表中的位置 order 中。

标签: clinuxubuntuprocesskernel

解决方案


  1. 获取您自己的 pid getpid
  2. 遍历/proc以数字开头的所有目录。
  3. 对于每个这样的目录,打开status文件。
  4. 阅读所有行,直到找到该PPid行。
  5. 如果 与PPid中的值匹配getpid,则将此目录名称添加到您的数组中。

这将为您提供其父进程是此进程的每个进程的 ID。


推荐阅读