如何从Linux内核中的PID获取过程描述符? [英] How can I get the process descriptor from a PID in Linux kernel?
问题描述
我试图弄清楚如何从PID中获取过程描述符.
I am trying to figure out how to get the process descriptor from a PID.
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)]
是指向PID值为pid
的task_struct
对象的指针.
The link seems to say that pidhash[pid_hashfn(pid)]
is a pointer to a task_struct
object whose PID is value pid
.
但是从《理解Linux内核》一书中似乎并非如此,该书讨论了Linux内核2.6.11.我不确定2.6.11和2.4中的相关代码是否相同.从书中,我了解到pidhash[pid_hashfn(pid)]
具有类型hlist_head
,它是指向hlist_node
对象的指针. hlist_node
对象是task_struct
对象的pids[0].pid_chain
.那么如何从pidhash[pid_hashfn(pid)]
获取task_struct
对象?
But that doesn't seem to be true from the book Understanding The Linux Kernel, which talks about Linux kernel 2.6.11. I am not sure if the relevant code is the same in 2.6.11 and in 2.4. From the book, I learned that pidhash[pid_hashfn(pid)]
has type hlist_head
, which is a pointer to an hlist_node
object. The hlist_node
object is pids[0].pid_chain
of a task_struct
object. Then how can I obtain the task_struct
object from pidhash[pid_hashfn(pid)]
?
请注意
-
我之所以问这个问题只是出于阅读《了解Linus内核》(Linux内核2.6.11)的目的,因此我没有询问最新的Linux内核版本,尽管您也可以使用它来提到在最新的Linux内核版本中是如何完成的.
I am asking this just for the purposes of reading Understanding the Linus Kernel (Linux kernel 2.6.11), so I am not asking about the recent Linux kernel versions, although it doesn't hurt that you can also mention how it is done in the recent Linux kernel versions.
I guess the difficulty I have here is related to my previous question Whose address shall the node of a linked list store: other node, or data structure having a node as a field?
谢谢.
推荐答案
In kernel 2.6.11 task_struct
contains array pids[PIDTYPE_MAX]
so that given task placed in several hash-tables simultaniously.
pidhash
包含指针到 PIDTYPE_MAX
哈希-桌子. pidhash[i]
是指向第 i 个哈希表的开头的指针.因此,pidhash[type][pid_hashfn(nr)]
是指向链表的指针.
pidhash
contains pointers to PIDTYPE_MAX
hash-tables. pidhash[i]
is a pointer to beginning of i-th hash-table. Thus, pidhash[type][pid_hashfn(nr)]
is a pointer to linked list.
It is better to find struct pid *
to entry in task's [pids[type]
] element with given pid type type
and pid nr
using kernel function find_pid(type, nr)
.
Then you can convert (non-NULL
) pointer to struct pid
into pointer to struct task_struct
using container-of
-based macro pid_task
.
这篇关于如何从Linux内核中的PID获取过程描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!