我试图弄清楚如何从PID中获取过程描述符。
从http://www.linuxforums.org/forum/kernel/153873-getting-task_struct-process-using-its-pid.html开始,对于Linux内核2.4
static inline struct task_struct *find_task_by_pid(int pid)
{
struct task_struct *p, **htable = &pidhash[pid_hashfn(pid)];
for(p = *htable; p && p->pid != pid; p = p->pidhash_next)
;
return p;
}
该链接似乎说pidhash[pid_hashfn(pid)]
是指向task_struct
对象的指针,该对象的PID为值pid
。
但是从《理解Linux内核》一书中似乎并非如此,该书讨论了Linux内核2.6.11。我不确定相关代码在2.6.11和2.4中是否相同。从书中,我了解到pidhash[pid_hashfn(pid)]
的类型为hlist_head
,它是指向hlist_node
对象的指针。 hlist_node
对象是pids[0].pid_chain
对象的task_struct
。然后如何从task_struct
获取pidhash[pid_hashfn(pid)]
对象?
请注意
我之所以问这个问题只是出于阅读《理解Linus内核》(Linux内核2.6.11)的目的,因此我没有询问最新的Linux内核版本,尽管您也可以使用它来提到在最新的Linux内核版本中是如何完成的。
我想我在这里遇到的困难与之前的问题Whose address shall the node of a linked list store: other node, or data structure having a node as a field?
谢谢。
答案 0 :(得分:1)
在内核2.6.11中,task_struct
包含数组pids[PIDTYPE_MAX]
,以便将给定任务同时放置在多个哈希表中。
pidhash
包含指向PIDTYPE_MAX
哈希表的指针。 pidhash[i]
是第 i 个散列表的开头的指针。因此,pidhash[type][pid_hashfn(nr)]
是指向链表的指针。
最好使用内核函数find_pid(type, nr)
在给定pid类型struct pid *
和pid pids[type]
下找到type
到任务的[nr
]元素中。
然后,您可以使用基于NULL
的宏pid_task
将指向struct pid
的(非{struct task_struct
)指针转换为指向container-of
的指针。