【问题标题】:How do I get the children PID by a system call?如何通过系统调用获取孩子的 PID?
【发布时间】:2021-07-20 01:30:31
【问题描述】:

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

我有这个文件,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,在其子进程列表中的位置顺序。

【问题讨论】:

  • 你的getcpid()总是从父进程调用,所以它总是从getpid()得到相同的pid,你为什么期待任何其他结果?又和内核有什么关系?
  • 你是否应该在内核中实现两个新的系统调用?
  • while (getppid() == original_parent); 的行是什么?您希望分叉的父级退出,然后让子级退出?
  • 您的getnchildren 也应该返回孩子的数量。它正在返回某个孩子的 pid。另外,该头文件如何访问.c文件中定义的pids[i]

标签: c linux ubuntu process kernel


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

这将为您获取其父进程是此进程的每个进程的 ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多