在进程描述符中,long类型的state描述了进程的当前状态。
如下所示:进程状态可以分为三大类:>0 停止运行,=0可以运行,-1不可运行。
实际上系统中的进程可以处于以下五种状态之一:
各状态的转换关系如下所示:
我们可以在内核代码中找到该定义:linux2.6.34/include/linux/sched.h#L183
/*
* Task state bitmask. NOTE! These bits are also
* encoded in fs/proc/array.c: get_task_state().
*
* We have two separate sets of flags: task->state
* is about runnability, while task->exit_state are
* about the task exiting. Confusing, but this way
* modifying one set can't modify the other one by
* mistake.
*/
#define TASK_RUNNING 0
#define TASK_INTERRUPTIBLE 1
#define TASK_UNINTERRUPTIBLE 2
#define __TASK_STOPPED 4
#define __TASK_TRACED 8
/* in tsk->exit_state */
#define EXIT_ZOMBIE 16
#define EXIT_DEAD 32
/* in tsk->state again */
#define TASK_DEAD 64
#define TASK_WAKEKILL 128
#define TASK_WAKING 256
#define TASK_STATE_MAX 512
#define TASK_STATE_TO_CHAR_STR "RSDTtZXxKW
内核中进程需要调整某个进程的状态。但是一般不是通过直接修改state的值来完成状态的改变,而是使用以下四个宏之一:
这些宏定义在linux2.3.34/include/linux/sched.h#L224
#define __set_task_state(tsk, state_value) \
do { (tsk)->state = (state_value); } while (0)
#define set_task_state(tsk, state_value) \
set_mb((tsk)->state, (state_value))
/*
* set_current_state() includes a barrier so that the write of current->state
* is correctly serialised wrt the caller's subsequent test of whether to
* actually sleep:
*
* set_current_state(TASK_UNINTERRUPTIBLE);
* if (do_i_need_to_sleep())
* schedule();
*
* If the caller does not need such serialisation then use __set_current_state()
*/
#define __set_current_state(state_value) \
do { current->state = (state_value); } while (0)
#define set_current_state(state_value) \
set_mb(current->state, (state_value))
从上述代码中可以清楚地看到set_current_state(state_value)等将于set_task_state(current, state_value)。
通过注释也能明白是否添加__的区别再去,set__current_state()包括了一个屏障,以便调用者在之后测试是否在睡眠时实际写入了state的值,而__set__current()则是简单地直接修改state的值。
注:current是一个宏,表示当前的进程,该宏的定义与体系结构相关,对于x86体系结构,其定义在linux2.6.34/arch/x86/include/asm/current.h#L17。由于current.h的内容较少,我把它完整地贴在这里了。
#ifndef _ASM_X86_CURRENT_H
#define _ASM_X86_CURRENT_H
#include
#include
#ifndef __ASSEMBLY__
struct task_struct;
DECLARE_PER_CPU(struct task_struct *, current_task);
static __always_inline struct task_struct *get_current(void)
{
return percpu_read_stable(current_task);
}
#define current get_current()
#endif /* __ASSEMBLY__ */
#endif /* _ASM_X86_CURRENT_H */
可执行程序代码是进程的重要组成部分,这些代码一般是从一个可执行文件载入到进程的地址空间中执行的。一般的程序在用户空间执行,但其请求系统调用或者触发异常时,其就陷入了内核空间。此时,称内核代表进程执行并处于进程上下文中。在此上下文中的current宏是有效的,除非在此间隙有更高优先级的进程需要执行并由调度器做出了相应调整,否则在内核退出时,程序恢复在用户空间执行。