轻松理解 struct pid

1. 基本概念

每个进程控制块都有4个有关ID、含义不同的值,内核根据它们组成了4个全局的2维的HASH表,每个进程都要链接到这四个不同含义的Hash表当中。

/* 4种类型的值*/
enum pid_type
{
    PIDTYPE_PID,   进程的PID
    PIDTYPE_TGID,  线程组ID
    PIDTYPE_PGID,  进程组ID
    PIDTYPE_SID,   会话ID
    PIDTYPE_MAX
};

struct task_struct {
    ......
/* PID/PID hash table linkage. */
    struct pid pids[PIDTYPE_MAX];
    ......
}

2. Hash表的数组
四个全局的Hash表头位于: static struct hlist_head *pid_hash[PIDTYPE_MAX];
每一个Hash表都是一个数组,每一个元素是一个Hash值的链表头。默认有2048个元素

-----------------------------------------------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |...|2047|  |
-----------------------------------------------------------------------------
  
3. Hash表数组元素的链表
我们拿进程的进程组ID(PIDTYPE_PGID)来举例,假如有3个进程组,分别是:

GROUP1: 
PID PGIP HASH_PGID (根据进程组ID[PGIP]得到的Hash值)
10  10   hash(10)=88    (进程组领头)
11  10   hash(10)=88
12  10   hash(10)=88

GROUP2: 
PID PGIP HASH_PGID (根据进程组ID[PGIP]得到的Hash值)
100  100   hash(100)=99    (进程组领头)
101  100   hash(100)=99
102  100   hash(100)=99

GROUP3: 
PID PGIP HASH_PGID (根据进程组ID[PGIP]得到的Hash值)
550  550  hash(550)=88     (进程组领头)
551  550  hash(550)=88
552  550  hash(550)=88

struct pid
{
    /* Try to keep pid_chain in the same cacheline as nr for find_pid */
    /* 值 */
    int nr;

    /* HASH_PGID 值相同、且为进程组领头的进程链在这里,如PID值为10和550的两个进程会通过这个字段链接,这里可以认为是1个维度链,非进程组的进程的这个域为NULL(这里不考虑其它3种类型的值) */
    struct hlist_node pid_chain; 

    /* PGID 值相同的进程链在这里,如上3个进程组,分别各自通过这个域链接起来,这里可以认为是第2个维度链 */
    /* list of pids with the same nr, only one of them is in the hash */
    struct list_head pid_list;
};

PGID的Hash表(即全局的pid_hash[PIDTYPE_PGID])

----
 0
----
 1
----
 2
----
 88  ---> 10  ---> 11 ---> 12      通过pid_list域链接
----      |
 ..       | 通过pid_chain域链接
----      |
 90       550 ---> 551 ---> 552    通过pid_list域链接
----
 ..
----
 99  ---> 100 ---> 101 ---> 102    通过pid_list域链接
----
2047
----

转载于:https://www.cnblogs.com/parrynee/archive/2010/01/14/1648152.html

猜你喜欢

转载自blog.csdn.net/weixin_33805743/article/details/93447491
PID