linux进程管理(1)---进程描述符
进程描述符
Linux使用进程描述符数据结构记录现场信息,然后给予进程描述符管理进程,包括进程的创建、调度、消亡等操作。
进程除了包括运行着的程序,还包括系统资源(当前CPU现场、调度信息、进程间关系等)。记录这些线程信息的数据结构就是进程描述符 task_struct(include/linux/sched.h中)
每个进程都有一个进程描述符,记录以下重要信息:进程标识符、进程当前状态、栈地址空间、内存地址空间、文件系统、打开的文件、信号量等。
获取方式:
在x86体系中,通过SP寄存器可以快速获取当前进程栈的位置;linux在栈的末端存放了一个特殊的数据结构thread_info,thread_info中存放了指向task_struct的指针。根据这个原理,首先当前进程通过SP寄存器获取栈的位置,然后根据栈大小(一般为1-2页)获取thread_info的地址,最后通过thread_info获取当前进程的地址。
linux不仅有进程ID,而且给每个线程也分配了线程ID。对于task_struct数据结构的成员来说,pid是线程ID,tgid是线程的进程ID(该进程也叫线程组长)。
进程状态:
调度程序根据进程状态决定是否调度进程,linux是用概念bitmap(位图)表示进程状态,一共有11种状态;这些状态可以分为三类:运行态、睡眠态、退出态。只有运行态的进程才能被调度程序调度;进程等待某个资源时处于睡眠态(可中断态、不可中断态);进程退出时处于退出态(僵尸态、死亡态)。其他的进程状态还包括停止态、跟踪态等,这些状态处于特定的使用场景中,就不介绍了。
- 运行态:进程在cpu上运行或者等待运行。
- 睡眠态:睡眠态分为可中断态和不可中断态。进程因为等待某个资源而处于睡眠状态。这两者的区别是不可中断态忽略发送过来的唤醒信号量,因为这个状态的进程获取了重要的系统资源,因此不能被轻易打断,该状态较少使用。
- 退出态:退出态分为僵尸态和死亡态。进程完成使命退出后处于僵尸态,此时进程的资源已经被释放,仅仅保留了task_struct结构(父进程可能使用);而死亡态不仅释放了所有资源,并且连task_struct结构也释放了。
系统给每个状态分配了一个字母缩写“RSDTtZXxKWP”,对应关系如下图所示。
#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_PARKED 512
#define TASK_STATE_MAX 1024
#define TASK_STATE_TO_CHAR_STR "RSDTtZXxKWP"
进程栈
linux系统为每个用户进程分配了两个栈:用户栈和内核栈。当一个进程在用户空间执行时,系统使用用户栈;当在内核空间执行时,系统使用内核栈。由于内核栈地址空间的限制,内核栈不会分配很大的空间。此外,内核进程只有内核栈,没有用户栈。
当进程从用户空间陷入到内核空间时,首先,操作系统在内核栈中记录用户栈的当前位置,然后将栈寄存器指向内核栈;内核空间的程序执行完毕后,操作系统根据内核栈中记录的用户栈位置,重新将栈寄存器指向用户栈。由于每次从内核空间中返回时,内核栈肯定已经使用完毕,所以从用户栈切换到内核栈时,只需要简单的将栈寄存器指向内核栈顶即可。
linux进程管理(1)---进程描述符 https://blog.csdn.net/luomoweilan/article/details/21196093
为了进程管理,内核必须对每个进程所做的事情进行清楚的描述。比如内核需要知道进程的优先级,进程当前的状态,在挂起和恢复进程的时候,需要对进程进行相应的操作。进程描述符还描述了进程使用的地址空间,访问的文件等等,这些都是进程描述符的作用。包括了很多进程属性的字段,还有一些字段包括了指向其他数据结构的指针,如下图:
-
TASK_RUNNING: 要么在CPU上执行,要么准备执行。
-
TASK_INTERRUPTIBLE: 进程被挂起(睡眠),直到某个为真的条件触发,产生一个硬件中断,释放进程正等待的系统资源,或传递一个信号都可以唤醒进程。
-
TASK_UNINTERRUPTIBLE: 不可中断的等待状态,与把信号传递给睡眠进程不能改变它的状态1。
-
TASK_STOPPED: 进程的执行被暂停,当收到SIGSTOP、SIGTSTP、SIGTTIN或SIGTTOU信号后,进入暂停状态。
-
TASK_TRACED: 跟踪状态,进程的执行由debugger程序暂停。
-
TASK_ZOMBIE: 进程执行被终止,但是父进程还没有发布wait4或waitpid系统调用返回有关死亡进程的信息。
-
TASK_DEAD: 僵死撤销状态。
task_struct 结构体:
<include/linux/sched.h>
struct task_struct {
// -1表示不可运行,0表示可运行,大于0表示停止
volatile long state;
void *stack;
atomic_t usage;
// 每进程标志,上下文定义
unsigned int flags;
unsigned int ptrace;
// 大内核锁的深度
int lock_depth;
#ifdef CONFIG_SMP
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
int oncpu;
#endif
#endif
// 优先级
int prio, static_prio, normal_prio;
unsigned int rt_priority;
const struct sched_class *sched_class;
struct sched_entity se;
struct sched_rt_entity rt;
#ifdef CONFIG_PREEMPT_NOTIFIERS
/* 同步的通知者 */
struct hlist_head preempt_notifiers;
#endif
unsigned char fpu_counter;
#ifdef CONFIG_BLK_DEV_IO_TRACE
unsigned int btrace_seq;
#endif
unsigned int policy;
cpumask_t cpus_allowed;
#ifdef CONFIG_TREE_PREEMPT_RCU
int rcu_read_lock_nesting;
char rcu_read_unlock_special;
struct rcu_node *rcu_blocked_node;
struct list_head rcu_node_entry;
#endif
#if defined(CONFIG_SCHEDSTATS) \
|| defined(CONFIG_TASK_DELAY_ACCT)
struct sched_info sched_info;
#endif
struct list_head tasks;
struct plist_node pushable_tasks;
struct mm_struct *mm, *active_mm;
/* 进程状态 */
int exit_state;
int exit_code, exit_signal;
// 在父进程终止时发送的信号
int pdeath_signal;
unsigned int personality;
unsigned did_exec:1;
unsigned in_execve:1;
unsigned in_iowait:1;
unsigned sched_reset_on_fork:1;
// pid和组id
pid_t pid;
pid_t tgid;
#ifdef CONFIG_CC_STACKPROTECTOR
unsigned long stack_canary;
#endif
/*
* 分别指向原父进程
* 最年轻的子进程
* 年幼的兄弟进程
* 年长的兄弟进程的指针
*/
struct task_struct *real_parent;
struct task_struct *parent;
struct list_head children;
struct list_head sibling;
// 线程组的组长
struct task_struct *group_leader;
struct list_head ptraced;
struct list_head ptrace_entry;
struct bts_context *bts;
/* PID/PID散列表的关系 */
struct pid_link pids[PIDTYPE_MAX];
struct list_head thread_group;
// 用于vfork()
struct completion *vfork_done;
// CLONE_CHILD_SETTID
int __user *set_child_tid;
// CLONE_CHILD_CLEARTID
int __user *clear_child_tid;
cputime_t utime, stime, utimescaled, stimescaled;
cputime_t gtime;
cputime_t prev_utime, prev_stime;
// 上下文切换计数器
unsigned long nvcsw, nivcsw;
// 单调时间
struct timespec start_time;
// 启动以来的时间
struct timespec real_start_time;
// 内存管理器失效和页交换信息
unsigned long min_flt, maj_flt;
struct task_cputime cputime_expires;
struct list_head cpu_timers[3];
/* 进程身份 */
const struct cred *real_cred;
const struct cred *cred;
struct mutex cred_guard_mutex;
struct cred *replacement_session_keyring;
char comm[TASK_COMM_LEN];
/* 文件系统信息 */
int link_count, total_link_count;
#ifdef CONFIG_SYSVIPC
/* ipc相关信息 */
struct sysv_sem sysvsem;
#endif
#ifdef CONFIG_DETECT_HUNG_TASK
unsigned long last_switch_count;
#endif
/* 当前进程特定于CPU的状态信息 */
struct thread_struct thread;
/* 文件系统信息 */
struct fs_struct *fs;
/* 打开文件信息 */
struct files_struct *files;
/* 命名空间 */
struct nsproxy *nsproxy;
/* 信号处理程序 */
struct signal_struct *signal;
struct sighand_struct *sighand;
sigset_t blocked, real_blocked;
sigset_t saved_sigmask;
struct sigpending pending;
unsigned long sas_ss_sp;
size_t sas_ss_size;
int (*notifier)(void *priv);
void *notifier_data;
sigset_t *notifier_mask;
struct audit_context *audit_context;
#ifdef CONFIG_AUDITSYSCALL
uid_t loginuid;
unsigned int sessionid;
#endif
seccomp_t seccomp;
/* 进程组的信息 */
u32 parent_exec_id;
u32 self_exec_id;
// 保护mm,files等信息的自旋锁
spinlock_t alloc_lock;
#ifdef CONFIG_GENERIC_HARDIRQS
/* IRQ处理进程 */
struct irqaction *irqaction;
#endif
spinlock_t pi_lock;
#ifdef CONFIG_RT_MUTEXES
struct plist_head pi_waiters;
struct rt_mutex_waiter *pi_blocked_on;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
struct mutex_waiter *blocked_on;
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
unsigned int irq_events;
int hardirqs_enabled;
unsigned long hardirq_enable_ip;
unsigned int hardirq_enable_event;
unsigned long hardirq_disable_ip;
unsigned int hardirq_disable_event;
int softirqs_enabled;
unsigned long softirq_disable_ip;
unsigned int softirq_disable_event;
unsigned long softirq_enable_ip;
unsigned int softirq_enable_event;
int hardirq_context;
int softirq_context;
#endif
#ifdef CONFIG_LOCKDEP
# define MAX_LOCK_DEPTH 48UL
u64 curr_chain_key;
int lockdep_depth;
unsigned int lockdep_recursion;
struct held_lock held_locks[MAX_LOCK_DEPTH];
gfp_t lockdep_reclaim_gfp;
#endif
/* 日志文件系统信息 */
void *journal_info;
/* 快设备信息 */
struct bio *bio_list, **bio_tail;
/* 虚拟内存状态 */
struct reclaim_state *reclaim_state;
struct backing_dev_info *backing_dev_info;
struct io_context *io_context;
unsigned long ptrace_message;
siginfo_t *last_siginfo;
struct task_io_accounting ioac;
#if defined(CONFIG_TASK_XACCT)
u64 acct_rss_mem1;
u64 acct_vm_mem1;
cputime_t acct_timexpd; /* stime + utime since last update */
#endif
#ifdef CONFIG_CPUSETS
nodemask_t mems_allowed;
int cpuset_mem_spread_rotor;
#endif
#ifdef CONFIG_CGROUPS
struct css_set *cgroups;
struct list_head cg_list;
#endif
#ifdef CONFIG_FUTEX
struct robust_list_head __user *robust_list;
#ifdef CONFIG_COMPAT
struct compat_robust_list_head __user *compat_robust_list;
#endif
struct list_head pi_state_list;
struct futex_pi_state *pi_state_cache;
#endif
#ifdef CONFIG_PERF_EVENTS
struct perf_event_context *perf_event_ctxp;
struct mutex perf_event_mutex;
struct list_head perf_event_list;
#endif
#ifdef CONFIG_NUMA
struct mempolicy *mempolicy;
short il_next;
#endif
atomic_t fs_excl;
struct rcu_head rcu;
// ...
进程资源限制
每个进程都有一组相关的资源限制(resource limit),限制指定了进程能使用的系统资源数量。这些资源限制避免用户过分使用系统资源(CPU,磁盘空间等)。堆当前进程的资源限制存放在current->signal->rlim字段,即进程描述符的一个字段。这个字段类型为rlimit结构的数组,每个资源限制对应一个元素:
struct rlimit {
unsigned long rlim_cur;
unsigned long rlim_max;
};
资源限制包括:
字段名 |
说明 |
RLIMIT_AS |
进程地址空间的最大数,以字节为单位,当进程使用malloc或相关函数的时候会检查这个值 |
RLIMIT_CORE |
内存信息转储文件的大小,当一个进程异常终止时,内核在进程的当前目录下创建内存信息转储文件之前检查这个值 |
RLIMIT_CPU |
进程使用CPU的最长时间,以秒为单位 |
RLIMIT_DATA |
堆大小的最大值 |
RLIMIT_FSIZE |
文件大小的最大值,如果进程把一个文件的大小扩充到这个值,内核就给这个进程发送SIGXFSZ信号 |
RLIMIT_LOCKS |
文件锁数量的最大值 |
RLIMIT_MEMLOCK |
非交换内存的最大值,当进程试图通过mlock或者mlockall锁住页框时,会检查这个值 |
RLIMIT_MSGOUEUE |
POSIX消息队列中的最大字节数 |
RLIMIT_NOFILE |
打开文件描述符的最大数,打开一个文件或复制一个文件时会检查这个值 |
RLIMIT_NPROC |
用户能拥有的进程最大数 |
RLIMIT_RSS |
进程锁拥有的页框最大数 |
RLIMIT_SIGPENDING |
进程挂起信号的最大数 |
RLIMIT_STACK |
栈大小的最大值,内核在扩充进程的用户态堆栈之前检查这个值 |
进程描述符 http://guojing.me/linux-kernel-architecture/posts/process-descriptor/#fn:3
这个讲得比较清楚:
【Linux】窥探Linux内核task_struct结构体
task_struct的定义及注释
Linux内核2.6.32版的task_struct源码
struct task_struct {
volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */
void *stack;
atomic_t usage;
unsigned int flags; /* per process flags, defined below */
unsigned int ptrace;
int lock_depth; /* BKL lock depth */
#ifdef CONFIG_SMP
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
int oncpu;
#endif
#endif
int prio, static_prio, normal_prio;
unsigned int rt_priority;
const struct sched_class *sched_class;
struct sched_entity se;
struct sched_rt_entity rt;
#ifdef CONFIG_PREEMPT_NOTIFIERS
/* list of struct preempt_notifier: */
struct hlist_head preempt_notifiers;
#endif
/*
* fpu_counter contains the number of consecutive context switches
* that the FPU is used. If this is over a threshold, the lazy fpu
* saving becomes unlazy to save the trap. This is an unsigned char
* so that after 256 times the counter wraps and the behavior turns
* lazy again; this to deal with bursty apps that only use FPU for
* a short time
*/
unsigned char fpu_counter;
#ifdef CONFIG_BLK_DEV_IO_TRACE
unsigned int btrace_seq;
#endif
unsigned int policy;
cpumask_t cpus_allowed;
#ifdef CONFIG_TREE_PREEMPT_RCU
int rcu_read_lock_nesting;
char rcu_read_unlock_special;
struct rcu_node *rcu_blocked_node;
struct list_head rcu_node_entry;
#endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */
#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
struct sched_info sched_info;
#endif
struct list_head tasks;
struct plist_node pushable_tasks;
struct mm_struct *mm, *active_mm;
/* task state */
int exit_state;
int exit_code, exit_signal;
int pdeath_signal; /* The signal sent when the parent dies */
/* ??? */
unsigned int personality;
unsigned did_exec:1;
unsigned in_execve:1; /* Tell the LSMs that the process is doing an
* execve */
unsigned in_iowait:1;
/* Revert to default priority/policy when forking */
unsigned sched_reset_on_fork:1;
pid_t pid;
pid_t tgid;
#ifdef CONFIG_CC_STACKPROTECTOR
/* Canary value for the -fstack-protector gcc feature */
unsigned long stack_canary;
#endif
/*
* pointers to (original) parent process, youngest child, younger sibling,
* older sibling, respectively. (p->father can be replaced with
* p->real_parent->pid)
*/
struct task_struct *real_parent; /* real parent process */
struct task_struct *parent; /* recipient of SIGCHLD, wait4() reports */
/*
* children/sibling forms the list of my natural children
*/
struct list_head children; /* list of my children */
struct list_head sibling; /* linkage in my parent's children list */
struct task_struct *group_leader; /* threadgroup leader */
/*
* ptraced is the list of tasks this task is using ptrace on.
* This includes both natural children and PTRACE_ATTACH targets.
* p->ptrace_entry is p's link on the p->parent->ptraced list.
*/
struct list_head ptraced;
struct list_head ptrace_entry;
/*
* This is the tracer handle for the ptrace BTS extension.
* This field actually belongs to the ptracer task.
*/
struct bts_context *bts;
/* PID/PID hash table linkage. */
struct pid_link pids[PIDTYPE_MAX];
struct list_head thread_group;
struct completion *vfork_done; /* for vfork() */
int __user *set_child_tid; /* CLONE_CHILD_SETTID */
int __user *clear_child_tid; /* CLONE_CHILD_CLEARTID */
cputime_t utime, stime, utimescaled, stimescaled;
cputime_t gtime;
cputime_t prev_utime, prev_stime;
unsigned long nvcsw, nivcsw; /* context switch counts */
struct timespec start_time; /* monotonic time */
struct timespec real_start_time; /* boot based time */
/* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */
unsigned long min_flt, maj_flt;
struct task_cputime cputime_expires;
struct list_head cpu_timers[3];
/* process credentials */
const struct cred *real_cred; /* objective and real subjective task
* credentials (COW) */
const struct cred *cred; /* effective (overridable) subjective task
* credentials (COW) */
struct mutex cred_guard_mutex; /* guard against foreign influences on
* credential calculations
* (notably. ptrace) */
struct cred *replacement_session_keyring; /* for KEYCTL_SESSION_TO_PARENT */
char comm[TASK_COMM_LEN]; /* executable name excluding path
- access with [gs]et_task_comm (which lock
it with task_lock())
- initialized normally by flush_old_exec */
/* file system info */
int link_count, total_link_count;
#ifdef CONFIG_SYSVIPC
/* ipc stuff */
struct sysv_sem sysvsem;
#endif
#ifdef CONFIG_DETECT_HUNG_TASK
/* hung task detection */
unsigned long last_switch_count;
#endif
/* CPU-specific state of this task */
struct thread_struct thread;
/* filesystem information */
struct fs_struct *fs;
/* open file information */
struct files_struct *files;
/* namespaces */
struct nsproxy *nsproxy;
/* signal handlers */
struct signal_struct *signal;
struct sighand_struct *sighand;
sigset_t blocked, real_blocked;
sigset_t saved_sigmask; /* restored if set_restore_sigmask() was used */
struct sigpending pending;
unsigned long sas_ss_sp;
size_t sas_ss_size;
int (*notifier)(void *priv);
void *notifier_data;
sigset_t *notifier_mask;
struct audit_context *audit_context;
#ifdef CONFIG_AUDITSYSCALL
uid_t loginuid;
unsigned int sessionid;
#endif
seccomp_t seccomp;
/* Thread group tracking */
u32 parent_exec_id;
u32 self_exec_id;
/* Protection of (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed,
* mempolicy */
spinlock_t alloc_lock;
#ifdef CONFIG_GENERIC_HARDIRQS
/* IRQ handler threads */
struct irqaction *irqaction;
#endif
/* Protection of the PI data structures: */
spinlock_t pi_lock;
#ifdef CONFIG_RT_MUTEXES
/* PI waiters blocked on a rt_mutex held by this task */
struct plist_head pi_waiters;
/* Deadlock detection and priority inheritance handling */
struct rt_mutex_waiter *pi_blocked_on;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
/* mutex deadlock detection */
struct mutex_waiter *blocked_on;
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
unsigned int irq_events;
int hardirqs_enabled;
unsigned long hardirq_enable_ip;
unsigned int hardirq_enable_event;
unsigned long hardirq_disable_ip;
unsigned int hardirq_disable_event;
int softirqs_enabled;
unsigned long softirq_disable_ip;
unsigned int softirq_disable_event;
unsigned long softirq_enable_ip;
unsigned int softirq_enable_event;
int hardirq_context;
int softirq_context;
#endif
#ifdef CONFIG_LOCKDEP
# define MAX_LOCK_DEPTH 48UL
u64 curr_chain_key;
int lockdep_depth;
unsigned int lockdep_recursion;
struct held_lock held_locks[MAX_LOCK_DEPTH];
gfp_t lockdep_reclaim_gfp;
#endif
/* journalling filesystem info */
void *journal_info;
/* stacked block device info */
struct bio *bio_list, **bio_tail;
/* VM state */
struct reclaim_state *reclaim_state;
struct backing_dev_info *backing_dev_info;
struct io_context *io_context;
unsigned long ptrace_message;
siginfo_t *last_siginfo; /* For ptrace use. */
struct task_io_accounting ioac;
#if defined(CONFIG_TASK_XACCT)
u64 acct_rss_mem1; /* accumulated rss usage */
u64 acct_vm_mem1; /* accumulated virtual memory usage */
cputime_t acct_timexpd; /* stime + utime since last update */
#endif
#ifdef CONFIG_CPUSETS
nodemask_t mems_allowed; /* Protected by alloc_lock */
int cpuset_mem_spread_rotor;
#endif
#ifdef CONFIG_CGROUPS
/* Control Group info protected by css_set_lock */
struct css_set *cgroups;
/* cg_list protected by css_set_lock and tsk->alloc_lock */
struct list_head cg_list;
#endif
#ifdef CONFIG_FUTEX
struct robust_list_head __user *robust_list;
#ifdef CONFIG_COMPAT
struct compat_robust_list_head __user *compat_robust_list;
#endif
struct list_head pi_state_list;
struct futex_pi_state *pi_state_cache;
#endif
#ifdef CONFIG_PERF_EVENTS
struct perf_event_context *perf_event_ctxp;
struct mutex perf_event_mutex;
struct list_head perf_event_list;
#endif
#ifdef CONFIG_NUMA
struct mempolicy *mempolicy; /* Protected by alloc_lock */
short il_next;
#endif
atomic_t fs_excl; /* holding fs exclusive resources */
struct rcu_head rcu;
/*
* cache last used pipe for splice
*/
struct pipe_inode_info *splice_pipe;
#ifdef CONFIG_TASK_DELAY_ACCT
struct task_delay_info *delays;
#endif
#ifdef CONFIG_FAULT_INJECTION
int make_it_fail;
#endif
struct prop_local_single dirties;
#ifdef CONFIG_LATENCYTOP
int latency_record_count;
struct latency_record latency_record[LT_SAVECOUNT];
#endif
/*
* time slack values; these are used to round up poll() and
* select() etc timeout values. These are in nanoseconds.
*/
unsigned long timer_slack_ns;
unsigned long default_timer_slack_ns;
struct list_head *scm_work_list;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
/* Index of current stored adress in ret_stack */
int curr_ret_stack;
/* Stack of return addresses for return function tracing */
struct ftrace_ret_stack *ret_stack;
/* time stamp for last schedule */
unsigned long long ftrace_timestamp;
/*
* Number of functions that haven't been traced
* because of depth overrun.
*/
atomic_t trace_overrun;
/* Pause for the tracing */
atomic_t tracing_graph_pause;
#endif
#ifdef CONFIG_TRACING
/* state flags for use by tracers */
unsigned long trace;
/* bitmask of trace recursion */
unsigned long trace_recursion;
#endif /* CONFIG_TRACING */
unsigned long stack_start;
};