Linux kernel Process Management 1——Conparison and Contrast between linux 2.4 VS linux 2.6 in process kernel stack layout

本文详细介绍了Linux内核2.4及2.6版本中进程内核堆栈的定义与实现方式,包括task_struct和thread_info结构体的作用,以及如何通过宏current获取当前进程描述符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于进程内核堆栈排部分析,转一篇不错的文章:

     在内核2.4中堆栈这么定义的:

         union  task_union{

            struct   task_struct  task;

            unsigned  long  stack[INIT_TASK_SIZE/sizeof(long)];

         };

     而INIT_TASK_SIZE只能是8k。

     

      内核为每个进程分配一个task_struct结构时,实际上分配2个连续的物理页面,如上图。底部用作task_struct结构(大小约1k字节), 结构的上面用作内核堆栈(大小约7k)。访问进程自身的task_struct结构,使用宏操作current,在2.4中定义如下:

     #define  current get_current()

     static  inline  struct  task_struct  *get_current(void)

     {

          struct  task_struct  *current;

          _asm_("andl  %%esp,%0;":"=r"(current):""(~8191UL));

          return current;

     }

     ~8191UL表示最低13位为0,其余位全为1.%esp指向内核堆栈中,当屏蔽掉%esp的最低13后,就得到这个“两个连续的物理页面”的开头,而这个开头正好是task_struct的开始,从而得到了指向task_struct的指针。

      在内核2.6中堆栈这么定义:

       union  thread_union

     {

          struct  thread_info  thread_info;

          unsigned  long stack[THREAD_SIZE/sizeof(long)];

     };

     根据内核的配置,THREAD_SIZE既可以是4k字节(1个页面)也可以是8k字节(2个页面)。thread_info是52个字节长。

     下图是当设为8kb时候的内核堆栈:Thread_info在这个内存区的开始处,内核堆栈从末端向下增长。进程描述符不是在这个内存区 中,而分别通过task与thread_info指针使thread_info与进程描述符互联。所以获得当前进程描述符的current定义如下:

     

 

     #define current  get_current()

     static  inline  struct  task_struct   *get_current(void)

     {

          return  current_thread_info()->task;

     }     

     static inline struct thread_info *current_thread_info(void)
{
       struct thread_info *ti;
       __asm__("andl %%esp,%0; ":"=r" (ti) : "" (~(THREAD_SIZE - 1)));
       return ti;
}

 

  根据 THREAD_SIZE 大小,分别屏蔽掉内核栈的 12-bit LSB(4K) 13-bit LSB(8K) ,从而获得内核栈的起始位置。

   struct thread_info {
      struct task_struct    *task;       /* main task structure */
      struct exec_domain    *exec_domain; /* execution domain */
      unsigned long           flags;       /* low level flags */
      unsigned long           status;       /* thread-synchronous flags */
      ... ..
}

 

参考:
1.      http://hi.baidu.com/zqfazqq/blog/item/12db349980343b0b6f068c5d.html
2.       Linux 内核源代码情景分析 ( 上册 , Page267)
3.       深入理解 Linux 内核 ( 3 , Page90, Page164)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值