李芳馨
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # OS-Chap3 - Process_行程 ###### tags: `作業系統 Operating System note`, `110-1`, `2021` ###### 參考資料 : [行程間的溝通](http://debussy.im.nuu.edu.tw/sjchen/OS/97Spring/Ch_7.pdf), [作業系統筆記](https://chentsungyu.github.io/2020/03/21/OS/%5BOS%5D%20%E4%BD%9C%E6%A5%AD%E7%B3%BB%E7%B5%B1%E7%AD%86%E8%A8%98-Process/), [作業系統-Process](https://www.namepluto.com/%E4%BD%9C%E6%A5%AD%E7%B3%BB%E7%B5%B1-process/), [作業系統簡介(下)](http://enews.open2u.com.tw/~noupd/book_up/1746/8719.htm) # Contents [TOC] --- # Process Concept ## Process v.s. Program - Process = 行程。**正在執行中的程式。** - 主動。 - **一個 program** 在 **memory(記憶體)** 中執行。 - 帶有 program counter,用來指出下一個指令的位置。 - Program = 程式 - 被動。 - 以 binary 的方式儲存在 disk (硬碟)中。 :star2: **一個 program,可以是多個 processes** :star: ∵ 多個使用者再執行同個 program >>>>>>>>>>>>>>>>>>>>>>>>> ----- ## 一個 Process 包含的東西 ![](https://i.imgur.com/vkssW0B.png) - Code Segment(=Text Section) - 程式碼、PC、暫存器…。 - Data Section(資料區間) - 全域變數(Global Variables) > - uninitialize : BSS > - initialize : - Stack - 暫時性資料 - 方便使用後直接 pop 掉(結束) - ex. 區域變數(Local Variables) - ex. 函式的參數(Function parameters) - Heap - 動態配置記憶體(變數/類別class) - Current Activity - Program Counter(計數器) : 存放下個被執行 program 的 address - Processor register : 就是處理器的暫存器 ## Five state of Process ### Process STD → 行程狀態圖 >- Process State Transition Diagram - 描述 **Process 由開始到結束的生命週期 (Life-Cycle)**,而一個Process在此週期中會經歷數種狀態。 ![](https://i.imgur.com/MzJbwoC.png) - ### Transition : 1. new → ready - admitted : 引入/產生一個新的 program 到電腦執行。 > - OS 在此時會確認有沒有足夠的資源去 create process,也會檢查權限(Protection),成功的話進入 Ready 2. ready → running - schedular dispatch : 從 memory 挑選一個 process 到 CPU 執行。 3. running → terminate :white_check_mark: - exit : process 完成他的 task/ job,就結束。 4. running → ready :heavy_check_mark: - 發生**短暫中止**時。 - interrupt/ 被高 priority process 插隊/ CPU Time Quantum 超過。 5. running → waiting (block) :white_check_mark: - 發生**較長時間的中止**時。 - wait for resource available - wait for I/O or event completion 6. waiting → ready :heavy_check_mark: - I/O or event completion :white_check_mark: 為 process **主動**放棄執行權 **non-preemptive** :heavy_check_mark: 為 process 被動放棄執行權 preemptive :exclamation: 若一個系統只有 process **主動** 放棄執行權,並重新進行排程時,此系統為 **non-preemptive** ,反之則稱為 preemptive :exclamation: > ref to chap 5 scheduling - ### State - new:產生新的 Process - 準備要將 Program load 到 memory,initial 各個 section - ready: - Process 競爭 CPU,在 queue 裡面等著被 OS schedule 後,被分配至CPU執行。 - 當 I/O 事件結束 or 執行期間(running)被Interrupt , Process 都會回到ready狀態 - running:執行中的 Process - wating:當有其他事件(Event)發生時,(ex.週邊設備的I/O),會進入暫時等待的狀態。 :heavy_exclamation_mark:Process此時雖然還在記憶體中,但不在Ready Queue - terminated:Process執行結束 - ### Queue > - 同下方 scheduling queue - Job Queue : 系統中的所有的 Process 形成的隊伍(list) - Ready Queue : 放在記憶體中多個 Process 形成的隊伍(list),準備隨時可以被分配至 CPU 內執行(running) :heavy_check_mark: 同個時間,一次只可以有一個 process 在 running 中執行:heavy_check_mark: :heavy_check_mark: 同個時間,可以有多個 processes 在 ready 和 waiting 中執行:heavy_check_mark: #### 此 STD 是針對 CPU 這項資源,且 data 都在 Memory中。 ## Process management - ### PCB(Process Control Block)行程控制表 > = TCB(Task Control Block) - 存在 memory 中。 - 每個 process 都有各自的一個 PCB。 - **用來記錄該 process 在被 context switch 前的資訊。** ## PCB 包含以下資訊 ![](https://i.imgur.com/MDjLQGK.png) - Pointer : 連接下一個 PCB (?) - Process State (行程的狀態) - process 在哪一個狀態 - ex. ready, waiting, running - Process number = Process ID (Process identify) - Process counter - 指明該 process 下一個要執行的指令 address。 - 在尚未要被 context switch 前,只會存和 PCB 頭的相對位置。 - 當準備被 context switch 前,會將 PCB head 的位置加上目前的相對位置,再存回此。 - CPU register - CPU scheduling information - priorities : Process 的優先順序 - memory manegement - memory limit - 0x00~0xC0000000 : memory (可連接至上方 : Process 包含的東西/Current Activity/Process register 的圖片) - accounting infor. - 用掉多少 CPU 的時間 - 使用 CPU 的最大時間量 - I/O status infor.(list of open file) - 尚未完成的I/O Request還有哪些 - 還在 I/O Queue中排隊之Process的編號 #### :heavy_exclamation_mark: OS 為了管理Process 方便,會存一份 PCB 在 OS 所在之 Monitor Area 中。:heavy_exclamation_mark: ## Context Switch - 轉換 CPU 至另一個 process 時(p0→1),必須將舊 process 的狀態存起來(存入PCB0),再載入新 process (從PCB1)的 data 至 CPU - Context Switch 所花費的時間對系統而言是 **額外的浪費 (overhead)**。 - 因為在 switch 的過程中,系統所做的事是不具有生産力的工作。 - Context Switch 的速度 - 主要取決於 **硬體 (hardware)** 支援的程度。 >- #### Solution to decrease context switch burder > 1. 提供多套 Register Sets > - 毎個Process皆可有自已的Register Set (若Register數量夠多) > - 當需要做Context Switching時,**OS只要切換 Register Set 的指標**到新Process即可 > - 速度快(不會用到 memory 存取)、但不適用 register 數量少的系統 > ![](https://i.imgur.com/z6eLbf9.png) > 2. 用 thread 代替 process > - 毎個 Process 都有自己的 PDB(私有),這些私有資訊會佔用 register。 > - **Threads之間彼此可以共享Memory Space** (ex. Code Section, Data Section, Open File) > - ∴ Context Switch 時**不須大量的 Memory Access** > 3. register 有限時 > - 當Register有限時,視哪一種類的Process切換較頻繁。 > - System Processes 與 User Processes 都有自已的Register Set > ∴當 User Process 與 System Process 之間 Context Switch 時,**OS只要改變Register Set的 pointer 即可**。 > ![](https://i.imgur.com/ipZg9L1.png) # Threads(線程) --- # Process Scheduling - Multiprogramming : CPU一直在running,達到最大效能 - Time sharing : 一直切換 CPU 執行的process,讓使用者覺得在互動 - processes 必須等到 CPU free 才能被重新排程 ## Scheduling Queue - process 在不同的 queue 做切換(在state的切換) - Job Queue(New state) - 在 disk 等待被抓入 ready 的所有行程 - Ready Queue(Ready State) - 在 memory 等待抓進去 running 的行程集合(process set) - Device Queue(Wait State) - 等待 I/O device 的行程集合(process set) ![](https://i.imgur.com/rUnJiDm.png) # Process Scheduling (行程的排程)--大排程 > 為了讓 CPU 發揮最大的效益,需 process scheduler 決定分配哪個 process 能使用CPU___猜。 ![](https://i.imgur.com/0izhrxL.png) ## Long-Term Scheduler - 亦稱 Job Scheduler - 從 job queue 挑選合適的 process ,能從 disk(磁碟) 排進 memory。(以控制 memory 內 process 的數量) ⇨ Control Multiprogramming Degree __(視CPU或Mem.的使用率高低而定) - 從 disk(磁碟) load 進 memory 的時間,相較於 memory 之間傳遞資料(Short-Term Scheduler) 所花費的時間長。 - ### disk → memory > - 執行頻率最低 > - 通常適用於Batch System,但不適用於Time-Sharing及Real-Time System。 > - 可調合CPU-Bound與I/O Bound之混合比例 (∵可視資源負荷決定載入Job與否)。 > UNIX/NT 沒有此 scheduler ## Short-Term Scheduler - 亦稱 CPU Scheduler - **Ready → Running** - 決定 memory 中的哪個 process 能排進 CPU running - 只作 memory 進入 CPU 的決定,花費的時間極短 - ### memory → CPU (?) > - 執行頻率最高 > - ∵毎個Process執行時狀況很多,如:不同情況的中斷…等。 > - 各種系統均需要 (Batch System, Time-Sharing, Real-Time System) > - ∵毎種系統都有CPU嘛。 > - 無法調整 Multiprogramming Degree 及 I/O Bound 與CPU Bound Job 之混合比例 ## Medium-Term Scheduler - **Virtual Memory** ???? - 保留long-term scheduler功能 - 採Swap(交換)的形式,將放在 memory(Ready Queue) 中的 Process 搬回 Disk(Job Queue) - Swapping - swap out : 從 memory 移除 process - swap in : 被 swap out 的process 再放回 memory - 目的 : 當記憶體內的行程太多,導致電腦的效能變差時,要將一些行程從 memory 移出,以減少行程搶用系統的 CPU ,以降低 multiprogramming process 的數量 (degree)。 - ### disk ↔ memory > - 執行頻率介於Long-Term與Short-Term之間 > - 用於 Time-Sharing System (Real Time, Batch不用) > - 可調控 Multiprogramming Degree > - 可調合I/O Bound與CPU Bound的比例 (當Long-Term Scheduler有誤判之時!! --- # Operation of Processes(Processes 的操作) ## Creation - parent process 創建 children processes(單個/多個),形成 process tree。 - child process 和 parent process 的差異 - 每個 process 有 unique id - 第一個關聯性,child process 建立之後,所需的 resources 由誰提供: - share all : parent 和 child 可以看到一模一樣的 content - subset : 行程配部份資源給子行程 - ex. global variable 看得到,動態 variable 看不到 - shared none : 父子行程無共享資源 - 兩個看到的東西完全不一樣 :heavy_check_mark: resource 不是 parent process 提供,就是 OS 提供 - 第二個關聯性,Parent 生出 child proces 後,兩者的互動模式: 1. execute concurrently : 父子同時執行 process - 交給 OS Scheduling 決定 2. parent 等到 child 執行完(terminate) - = parent process 做了 fork 之後,就會進到 waiting queue 裡面 - 第三個關聯性,child process 的工作項目: - Old implementation : child 完全 copy parent( = duplicate) - Current implementation : Copy-on-write 的方式去儲存 ,run time,,修改值的時候再做分家 ### 相關的 system call - fork() - Memory space of fork() > - parent process 和 child process 有各自獨立的 memory space > ref. [fork()](https://burweisnote.blogspot.com/2017/09/fork.html) - execlp() - Load a new binary file into memory ,舊的 code 丟了 - ex. 在 web download 其他 file(ex.ppt, pdf ...),下載完成後要開啟時,會連到其他file 做開啟的動作。(開啟後就不甘 web 的事 = 不甘 parent process 的事) - wait() - 通常是 concurrently 執行,所以可以透過 waiting 調整 - parents 會等待其中一個 child processes 執行完成 #### fork()、execlp() memory space 的 Example ![](https://i.imgur.com/EZwNu1i.png) ## Termination ### 相關的 system call - exit() - abort() - wait() # Important!!! ## Orphan(孤兒) && Zombie(殭屍) - parent 死了(terminate),child 會變 orphan(孤兒)! - parent 睡了(sleep),child 事情做完會變 zombie(殭屍)! --- # IPC(Inter-Process Communication) - 分為 independent 和 cooperating > - indepensent > - 不受其他 processes 的影響,或無法影響其他 processes 的執行。 > - 獨立的Process之間不會有任何共享資料。 > > - cooperating > - 會受到其他 processes 的影響,或影響其他 processes 的執行。 > - 故 Process 之間會有共享的資料,需要有進行資訊交換的管道。 > - processes 之間合作的理由 > 1. infor. sharing > 2. speedup computation > 3. Modularity > 以模組化的方式建構 system ,讓 system 分配它的功能到各個 processes。 > 4. Convenience > ex. 單一使用者同時做編輯、列印、編譯。 ## Model(常見作法) ![](https://i.imgur.com/MMmjFBo.png) ### Message passing - Process 間使用 kernel 中的 shared memory 產生連接通道(communication link#→message queue)溝通。 > (非藉助共享變數 shared variables) - 做 communication 的過程如下 → OS提供的東西 1. 建立 communication link → 會有 communication link 存在 processes 之間 2. 傳遞/交換信息(message) → send/receive messge 3. 傳輸完畢 → release link - :heavy_exclamation_mark: **若傳遞少 data 較沒效率** >#### 實作 Communication Link 的方式 >- Physical: - Shared memory - Hardware bus - Network >- Logical: - Direct or indirect - Synchronous or asynchronous - Automatic or explicit buffering #### 通訊(Communication)的方式 - #### direct (直接傳訊息) ![](https://i.imgur.com/3yRzEK6.png) - #### indirect (間接傳遞) ![](https://i.imgur.com/E03jZRO.png) | Direct | Indirect | |:---------------------------------------------------:|:--------------------------------------------------:| | 建立 link 用 send/receive 傳送訊息 | 訊息從 mailbox 裡直接接收(**只能共享mailbox**資料) | | 為自動建立 (established automatically) | 每個mailbox都有個獨特的ID(unique id) | | 一個Link剛好連接一對Process(One-to-One) | 一對process之間,可能存在多條Link | | 每個行程必須要明確地命名 | 要建立連結,只能是行程共享郵箱 | | Link 可以是 unidirectional,但通常是 bi-directional | Link 可能是 unidirectional 或 bi-directional | - 間接傳遞(indirect)的過程中,通訊的同步非常重要,分作兩種形式: - blocking - Blocking send:訊息傳遞出去,Process被Block阻擋,直到對方訊息收到才可再傳送。 - Blocking receive:不做任何動作,直到訊息送來,再回傳收到的資訊。 - non-blocking - Non-blocking send:不管對方有無收到訊息,持續發送訊息給對方。 - Non-blocking receive:接收者只接收有效訊息,或是沒有訊息。 ### Shared Memory - process 之間利用 shared memory 交換資訊、彼此溝通。(**非使用 kernel提供的 space**) - 使用記憶體位置(memory address)來存取 data - 利用 read/write 資料來完成資訊交換 - :heavy_exclamation_mark: OS只提供 shared memory space,行程間的 **sychronization** 則需要由 programmer(user) 負責,OS不提供額外的資源。 #### → producer會把資料放進buffer內(write) #### → consumer會去同一個buffer把資料取出來(read) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> --- | | Share Memory | Message Passing | | -------- |:----------------------------------------:| ---------------------------------------------------- | | 溝通方式 | 共享一部分的記憶體(透過共享變數存取資料) | Process 之間建立 Communication Link | | 共享性 | 共享變數所有 process 皆可存取 | process 間有專屬的 Link,不會隨意被其他 Process 共用 | >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> --- ## Producer-Consumer Problem

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully