Linux 内核中的 task_struct
结构详解
task_struct 是 Linux 内核中用来表示 进程(或者线程) 的核心结构体,是操作系统调度、管理和追踪进程的基础。该结构体非常庞大,包含了大量字段,用于管理进程的各种状态。
🧠 task_struct
的主要组成结构(按功能分类)
1. 进程标识
用于标识进程的唯一性:
1 2 3
| pid_t pid; pid_t tgid; struct pid *thread_pid;
|
2. 进程状态与调度相关
包括进程状态、优先级、调度器策略等:
1 2 3 4 5 6
| volatile long state; unsigned int flags; int prio; int static_prio; int policy; struct sched_entity se;
|
3. 父子进程关系
记录进程之间的层级关系:
1 2 3 4
| struct task_struct *real_parent; struct task_struct *parent; struct list_head children; struct list_head sibling;
|
4. 内存管理
与地址空间和虚拟内存相关的信息:
1 2
| struct mm_struct *mm; struct mm_struct *active_mm;
|
5. 文件系统与文件描述符表
1 2
| struct fs_struct *fs; struct files_struct *files;
|
6. 信号处理
1 2 3
| struct signal_struct *signal; struct sighand_struct *sighand; sigset_t blocked;
|
7. 命名空间(Namespace)
1
| struct nsproxy *nsproxy;
|
8. CPU 和上下文切换相关
1 2 3
| struct thread_struct thread; int on_cpu; struct cpumask *cpus_allowed;
|
9. 时间统计
10. Cgroup 与资源限制
1
| struct css_set *cgroups;
|
11. 调试与追踪
12. 内核同步与锁
13. 其他常用字段
1 2 3
| char comm[TASK_COMM_LEN]; struct task_struct *group_leader; int exit_code;
|
🔧 小结图解(简略)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| task_struct ├── 进程标识:pid, tgid ├── 状态与调度:state, prio, policy, se ├── 父子关系:parent, children ├── 内存管理:mm, active_mm ├── 文件系统:files, fs ├── 信号处理:signal, sighand ├── 命名空间:nsproxy ├── CPU调度:thread, on_cpu ├── 时间统计:utime, stime ├── Cgroup:cgroups ├── 同步锁:alloc_lock ├── 调试追踪:ptrace └── 通用信息:comm, exit_code
|
该结构体可能会在不同版本的内核中有所变动,但整体结构和这些功能模块是核心。