c - 如何通过系统调用获取孩子的 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 中。
解决方案
- 获取您自己的 pid
getpid
。 - 遍历
/proc
以数字开头的所有目录。 - 对于每个这样的目录,打开
status
文件。 - 阅读所有行,直到找到该
PPid
行。 - 如果 与
PPid
中的值匹配getpid
,则将此目录名称添加到您的数组中。
这将为您提供其父进程是此进程的每个进程的 ID。
推荐阅读
- c# - 使用 c# 和 winforms 在标签中显示最后保存的用户 ID 和名称
- r - 如何使用不均匀列表创建数据框
- xamarin - MasterDetailPage:接受页面以外的内容
- python - 在 Keras 中建立功能模型
- python - 从固定日期和预期的未来事件计算结果
- ruby - 如何屏蔽 URL 导轨
- node.js - save() 忽略“updateAt”字段更改
- matplotlib - 在 matplotlib 中部分斜体的情节标题
- artifactory - 具有许多目录的 Artifactory 存储库浏览器
- swagger - 是否可以将 spring-auto-restdocs 与 Swagger/SpringFox 一起使用?