微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过系统调用获取孩子的 PID?

如何解决如何通过系统调用获取孩子的 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],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。

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。