快轉到主要內容
  1. 文章/

OSTEP 第四章:Process 重點整理

·286 字·2 分鐘

Heptabase 筆記

核心問題:如何讓電腦同時擁有很多 CPU 的假象?

在解決這個問題前,我們先認識幾個東西。

Program #

什麼是 Program ? #

Program 是我們寫下的 code ,尚未被執行的 code 。

Process #

什麼是 Process ? #

Process 是執行中的 Program (running program)。

從程式的角度,你也可以把它看成是一個可以被建立、使用的物件。

// the registers xv6 will save and restore
// to stop and subsequently restart a process
struct context {
    int eip;
    int esp;
    int ebx;
    int ecx;
    int edx;
    int esi;
    int edi;
    int ebp;
};
// the different states a process can be in
enum proc_state { UNUSED, EMBRYO, SLEEPING,
RUNNABLE, RUNNING, ZOMBIE };
// the information xv6 tracks about each process
// including its register context and state
struct proc {
    char *mem; // Start of process memory
    uint sz; // Size of process memory
    char *kstack; // Bottom of kernel stack
    // for this process
    enum proc_state state; // Process state
    int pid; // Process ID
    struct proc *parent; // Parent process
    void *chan; // If non-zero, sleeping on chan
    int killed; // If non-zero, have been killed
    struct file *ofile[NOFILE]; // Open files
    struct inode *cwd; // Current directory
    struct context context; // Switch here to run process
    struct trapframe *tf; // Trap frame for the
    // current interrupt
};

Process API #

作業系統將 Running program 抽象成一個 Process;作業系統也針對 Process 提供了一些有用的 API 方便讓我們可以操作。

  • Create
  • Destory
  • Wait
  • Miscellaneous Control
    • e.g., suspend or resume
  • Status
    • 查詢狀態

後面章節會討論一些真正的 Process API

Process 狀態 #

真實世界中 Process 有許多種狀態,我們這裡指舉例幾個

  • Running
  • Ready
  • Blocked

Process 的狀態可以因不同事件而切換

Program 是如何變成 process 的呢? #

  1. 作業系統會把 Program(code, static data) 從硬碟裡讀出來並載入到記憶體裡
  2. 初始化 stack (e.g., local variables, function parameter, retrun address, etc…)
  3. 初始化 heap
  4. 初始化相關的 I/O (如果需要的話)
  5. CPU 執行指令

分時機制(time-sharing) #

分時機制的基本概念是短時間內先執行了 Process A 暫停,然後執行 Process B 。如此反覆。

因為 CPU 的執行速度太快 (1 ms),以至於讓使用者以為,許多任務都是同時執行的。

挑戰 #

Context switch #

在不同的 Process 之間轉換 OS 會需要儲存、載入一些資訊好讓 CPU 知道需要執行哪一個 Process 。

這中間也會有不小的消耗,如何在多工與效率間平衡點,就顯得相當重要。

控制權 #

當 CPU 在執行 Process 的時候,就代表作業系統沒有被執行(作業系統也可以理解成一個 running program),那如何在執行其他程式時,適時的把控制權交還給作業系統?