Linuxprocesssystem

Linux 中的行程 (Process) 被稱為 Task,其資料結構是一個稱為 task_struct 的 C 語言結構,該結構所記錄的欄位相當多,在 Linux 2.6.29.4 版當中光是該結構的宣告就占了 306 行的程式碼,範例 10.32範例 10.2顯示了該結構的開頭與結束部分,由此可見要實作一個作業系統是相當不容易的工程。

範例 10.32 Linux 中的 Task 之結構
行號 Linux 2.6.29.4 版核心原始碼 include/linux/sched.h 檔案

1115
1116
1117
1118
1119
1120

1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273

1417
1418
1419
1420
1421
… …
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;

/* 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;

#ifdef CONFIG_TRACING
/* state flags for use by tracers */
unsigned long trace;
#endif
};

Linux 的行程結構中包含了一個 thread 欄位 (1264 行),該欄位用來儲存與 CPU 相關的暫存器、分段表等資訊,由於暫存器資訊是與處理器密切相關的,所以每一種 CPU 都會擁有不同的執行緒結構,IA32 (x86) 的thread_struct之程式片段如範例 10.43範例 10.3所示。

範例 10.43 Linux 中的IA32 (x86) 處理器的Thread 之結構
行號 Linux 2.6.29.4 版核心原始碼 arch/x86/include/asm/processor.h 檔案

391
392
393
394
395
… …
struct thread_struct {
/* Cached TLS descriptors: */
struct desc_struct tls_array[GDT_ENTRY_TLS_ENTRIES];
unsigned long sp0;
unsigned long sp;

Linux 行程的狀態有 Running, Interruptible, Uninterruptible, Zombie, Stopped 等五種,但後來又增加了 Traced, EXIT_DEAD, TASK_DEAD, TASK_WAKEKILL 等四種,形成了九種狀態??這裡建議講解這九種狀態的關係,而不是程式中定義的常數?? (2.6.29.4 版),如範例 10.54範例 10.4所示。

範例 10.54 Linux 中的行程狀態
行號 Linux 2.6.29.4 版核心原始碼 include/linux/sched.h 檔案

174
175
176
177
178
179
180
181
182
183
184
… …
#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

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License