查找任务 'target' 是否是任务 `ancestor` 的后代(linux 内核任务)
find if task 'target' is descendant of task `ancestor` (linux kernel tasks)
这是我目前的解决方案:
int is_descendant(task_t* ansc, task_t* targ)
{
task_t* p_tmp;
for(p_tmp = targ ; (p_tmp) && (ansc) && (p_tmp->pid) && (p_tmp->pid != ansc->pid) ; p_tmp = p_tmp->p_pptr) ;
if((!p_tmp) || (!current) || (!p_tmp->pid)) return -ESRCH;
return 0;
}
它有效,但我不确定几件事:
不检查 p_tmp->pid == 0
是否永远迭代,这是否意味着第一个进程的父指针不为 NULL?
是否需要检查p_tmp
或ansc
是否为NULL?
有更好的方法吗? (使用 O(1) space 完成。)
宏与函数 ?
谢谢
至于4.:你希望通过宏而不是函数得到什么?使用函数而不使用宏几乎总是更好。
宏的基本问题包括(但不一定限于)以下内容:
- 宏很容易出错,因为它们使用文本替换。他们可能并不总是按照您的期望去做,并且发现这些错误并不总是微不足道的。
- 宏可能会导致不必要的副作用,例如多次计算表达式。
- 宏不能 return 您的
return NOTDESCENDANT
行中的值。 (如果在具有匹配 return 类型的函数内部使用宏,它可能会起作用。)
- 编写(可能还有阅读)跨越多行的宏是一件痛苦的事情。
这里也讨论了所有这些要点:Macro vs Function in C你也可以在那里看到所有这些问题的一些例子。
底线:如有疑问,请始终使用函数或内联函数而不是宏。
does that mean that the parent pointer of the first process is not NULL ?
根据 sources,init 任务 的父项是此任务本身。
is it necessary to check if p_tmp
or ansc
are NULL ?
父任务 (->p_pptr
) 不能为 NULL,因此 p_tmp
也不能为 NULL。
ansc
是函数的一个参数,在函数体内没有被修改。函数是否应该接受 NULL 取决于设计。
is there a better way to do this ? (using O(1) space compl.)
由于任务存储的指针既不指向其所有祖先也不指向其所有后代,因此您无法以常量 time (O(1)) 执行操作。
int is_descendant(task_t* ansc, task_t* targ)
{
task_t* p_tmp;
if(ansc->pid == 0) return 0; // init task is ansestor for all tasks.
for(p_tmp = targ; p_tmp->pid; p_tmp = p_tmp->p_pptr)
if(p_tmp == ansc) return 0; // Found path to 'ansc'
// Reach init task without touching 'ansc'.
return 1;
}
这是我目前的解决方案:
int is_descendant(task_t* ansc, task_t* targ)
{
task_t* p_tmp;
for(p_tmp = targ ; (p_tmp) && (ansc) && (p_tmp->pid) && (p_tmp->pid != ansc->pid) ; p_tmp = p_tmp->p_pptr) ;
if((!p_tmp) || (!current) || (!p_tmp->pid)) return -ESRCH;
return 0;
}
它有效,但我不确定几件事:
不检查
p_tmp->pid == 0
是否永远迭代,这是否意味着第一个进程的父指针不为 NULL?是否需要检查
p_tmp
或ansc
是否为NULL?有更好的方法吗? (使用 O(1) space 完成。)
宏与函数 ?
谢谢
至于4.:你希望通过宏而不是函数得到什么?使用函数而不使用宏几乎总是更好。
宏的基本问题包括(但不一定限于)以下内容:
- 宏很容易出错,因为它们使用文本替换。他们可能并不总是按照您的期望去做,并且发现这些错误并不总是微不足道的。
- 宏可能会导致不必要的副作用,例如多次计算表达式。
- 宏不能 return 您的
return NOTDESCENDANT
行中的值。 (如果在具有匹配 return 类型的函数内部使用宏,它可能会起作用。) - 编写(可能还有阅读)跨越多行的宏是一件痛苦的事情。
这里也讨论了所有这些要点:Macro vs Function in C你也可以在那里看到所有这些问题的一些例子。
底线:如有疑问,请始终使用函数或内联函数而不是宏。
does that mean that the parent pointer of the first process is not NULL ?
根据 sources,init 任务 的父项是此任务本身。
is it necessary to check if
p_tmp
oransc
are NULL ?
父任务 (->p_pptr
) 不能为 NULL,因此 p_tmp
也不能为 NULL。
ansc
是函数的一个参数,在函数体内没有被修改。函数是否应该接受 NULL 取决于设计。
is there a better way to do this ? (using O(1) space compl.)
由于任务存储的指针既不指向其所有祖先也不指向其所有后代,因此您无法以常量 time (O(1)) 执行操作。
int is_descendant(task_t* ansc, task_t* targ)
{
task_t* p_tmp;
if(ansc->pid == 0) return 0; // init task is ansestor for all tasks.
for(p_tmp = targ; p_tmp->pid; p_tmp = p_tmp->p_pptr)
if(p_tmp == ansc) return 0; // Found path to 'ansc'
// Reach init task without touching 'ansc'.
return 1;
}