【发布时间】:2021-07-31 21:24:21
【问题描述】:
我正在尝试编写一个函数,对除主进程之外的子进程的 pid 进行递归求和(如果 C 是 B 的儿子,而 B 是 A 的儿子,那么我想要 pid(B)+pid(C))
所以我写了:
int get_children_sum_internal(const struct task_struct *current) {
int result = current->pid;
struct list_head *pos;
list_for_each(pos, ¤t->children)
{
result+=pos->pid;
}
return result;
}
asmlinkage int get_children_sum(void) {
if (list_empty(¤t->children))
{
return;
}
return get_children_sum_internal(current);
}
但我收到一个错误,因为 current 来自 task_list 类型,而 pos 来自 list_head 类型。我该如何解决这个问题?
【问题讨论】:
-
我认为这不能解决您的问题,您仍然需要在
list_entry函数中使用sibling而不是children。但是当你运行代码时会发生什么?它是否有效或您是否发现任何错误? -
我没有发现任何问题,为什么这仍然是错误的?我正在使用 list_entry
-
@mr_calc 我认为您误解了
list_head结构在内核中的工作方式。有两种思考方式。 1)概念上list_head是什么?它是列表中的一个条目。因此,当您从父进程中获取children变量时,您实际上是在获取列表中第一个子进程的条目。那么如何从第一个条目中获取列表中的下一个条目?list_for_each函数集只是通过执行pos= pos->next将当前条目pos向前移动。但这些只是条目(指针),而不是实际的对象(在本例中为task_structs)本身。 -
@mr_calc 也尽量不要以显着改变原始问题的方式编辑您的原始帖子。否则,标题、问题和答案会让其他不了解您所做更新的第一次阅读本文的人感到困惑。
标签: c linux process linux-kernel operating-system