【问题标题】:How can I get the process descriptor from a PID in Linux kernel?如何从 Linux 内核中的 PID 获取进程描述符?
【发布时间】:2018-09-17 05:02:54
【问题描述】:

我正在尝试弄清楚如何从 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

但在《Understanding The Linux Kernel》一书中似乎并非如此,该书谈到了 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对象呢?

注意

谢谢。

【问题讨论】:

    标签: linux process linux-kernel pid


    【解决方案1】:

    在内核 2.6.11 中 task_struct 包含数组 pids[PIDTYPE_MAX] 以便给定任务同时放置在多个哈希表中。

    pidhash 包含指向PIDTYPE_MAX 哈希表的指针。 pidhash[i] 是指向第 i 哈希表开头的指针。因此,pidhash[type][pid_hashfn(nr)] 是一个指向链表的指针。

    最好使用内核函数find_pid(type, nr) 找到struct pid * 以进入具有给定pid 类型type 和pid nr 的任务的[pids[type]] 元素。

    然后您可以使用基于container-of 的宏pid_task 将(非NULL)指向struct pid 的指针转换为指向struct task_struct 的指针。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多