111級中興大資工
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • 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 Help
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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    --- tags: 大三 --- # 作業系統期中筆記 I - 國立中興大學大資訊工程系 Autumn 2020 CH1-3 ![](https://img.shields.io/badge/dynamic/json?color=blue&label=%E7%B8%BD%E8%A7%80%E7%9C%8B%E6%95%B8&query=%24.viewcount&suffix=%E4%BA%BA%E6%AC%A1&url=https%3A%2F%2Fhackmd.io%2F19Osz5jKSQqIHk6Tl3OP2g%2Finfo) ![](https://img.shields.io/badge/%E5%91%BD%E4%B8%AD%E7%8E%87-極高-yellowgreen) [作業系統期中筆記整理 - 國立中興大學大資訊工程系 Autumn 2020 (Part II)](https://hackmd.io/6i05ZGzzSBCpF_7FE50VIQ) ## CH1 Introduction Computer is consisted of: 1. hardware > OS have **device driver(software)** for each **device controller(hardware)** for management 2. operating system > Between a user/app and the computer hardware > > Goal: > Manage the computer hardware and provides an environment for apps to run 3. system and application programs 4. users ### Event-Driven OS #### Interrupt > **Device controller raises an interrupt** by asserting a signal on the interrupt-request line > > CPU **catches** the interrupt > > CPU **dispatches** it to the interrupt handler > > Interrupt handlers **serve** the device #### Trap (aka. exception) > A software-generated interrupt caused by > 1. Error (e.g. 除以零) > 2. Request for operating system service (e.g. system call) *Q: Please list the three situations that the CPU would enter into the kernel mode.* *A: 1. system call 2. interrupt 3. trap* ### OS structure 1. single-programming system > One job at time -- very inefficient 2. multi-programming system > **只有 I/O 時才會切換 process** > run multiple programs keep either the CPU or I/O devices busy at all times 3. time-sharing system > A logical extension of multi-programming > 硬體設定計時器時間到了切換 processes ### Dual-mode and Multi-mode of Operations To ensure proper execution of the system, most distinguish between the execution of OS code and user-defined code. Thus, hardware supports dual-mode or multi-mode operations. + Allow OS to protect itself and other system components. + Privileged instruction(特權指令) can only execute in kernel mode. 有些操作只有 OS 有權限做到,比如 CLI (一種拒絕 cpu interrupt 的指令),只有 OS 有權使用該指令 Modern CPUs have at least two execution modes -- user modes and monitor modes(aka. supervisor mode, kernel mode). e.g. x86 has 4 kinds of modes, ARM has 7 kinds of modes. ## CH2 OS Structure OS provides services to programs and users. Two sets of services: 1. Provides functions helpful to the user + user interface > CLI(command-line Interface), GUI (Graphical User Interface) + program execution + I/O operations + File-system manipulation + Communications + Error detection 2. Ensure the efficient operation of the system via resource sharing + Resource allocation > When multiple users running concurrently, resources must be allocated to each of them + Logging (記錄) > Keep track of which users use how much and what kinds of resources + Protection and security ![](https://i.imgur.com/OR2dLfc.png) ### System calls + An interface for app program to use OS services + e.g., open(), read(), write(), close(), ...etc + Even simple program may make heavy use of system calls However, system calls are often accessed by programs via a high-level **Application Program Interface(API)** rather than directly call the system call. Three most common APIs + Win32 API for windows + POSIX API for POSIX-bases systems + Java API for the Java virtual machine(JVM) There are managed by run-time support library Standard C Library: C programming uses functions defined in libc, which provides a wrapper for a portion of system calls. (比如 printf 就是把 system call write() 做包裝,讓碼農直接 call printf 而不需要用 write()) ![](https://i.imgur.com/KpJFA43.png) Why use APIs rather than system call? 1. portability (可以跨平台) 2. Easier to use (printf 比 write 好用) ### Why app are OS specific Fundamentally, app compiled on one OS usually not executable on other OSes, due to 1. At the system level + OSes have different binary format for executable + ELF for unix-based os + PF for windows + CPUs have different instruction sets + OSes define their own system call 2. At the application level + An applications call one set of APIs will ot work on an OS without the same API ### OS design and implementation User goals and System goals + User goals – OS should be convenient to use, easy to learn, reliable, safe, and fast + System goals – OS should be easy to design, implement, and maintain, as well as flexible, reliable, error-free, and efficient 早期的作業系統如 MS-DOS 是用 intel-8088 asm 寫的,用組語寫的好處是跑的比 C 快,但其實並沒有,因為現代強大的編譯器優化過後 C 跑的跟組語差不多快了。主要還是差在演算法和資結。 ### OS structure 1. Monolithic structure > 早期的作業系統採用此法 > **pros**: very little overhead > **cons**: difficult to implement and extend 2. Layered approach > OS is divided into a number of layers > **pros**: simplicity of construction and debugging. information hiding (do not have to know the details of other layers, 類似網際網路 5 層架構,大家各司其職) > **cons**: hard to determine the number of layers and hard to define functionality of each layer. 另外這個方法慢到靠北 (less efficient) 3. Microkernels > motivation: due to UNIX became large and difficult to manage > **pros**: easier to extend OS, easier to port the OS to new architectures, more reliable and more secure > **cons**: performance overhead by message passing between services via <u>communication facility</u> > e.g., Windows NT (microkernel), Windows XP (monolithic kernel) 4. Modules > An OS consists of a core kernel and a set of loadable kernel modules (LKMs) that can dynamically loadable at run time > **pros**: > + more flexible than layered system because a module can call any other module > + more efficient than microkernel (kernel module communications is **function call, not by message passing(message passing = communication facility 這個詞有可能會考哦**) > > **cons**: > 講議沒寫 5. Hybrid systems > 大雜燴 > Linux: monolithic + modular > Windows: monolithic + micro kernel + modular ### System boot Two-step booting process in PCs > Bootstrap loader in ROM → boot program on disk → kernel bootstrap program or bootstrap loader are + small piece of code stored in ROM or EEPROM + modern system replace BIOS with Unified Extensible Firmware Interface (UEFI) + locate the kernel, load it into memory, and start its execution. ## CH3 Process ![](https://i.imgur.com/RinJsGD.png) + stack: variables in function + heap: dynamic variables + data + uninitialized data (.bss) + initialized data (.data) + text (.code) ### Process control block (PCB) *Q: What is purpose of process control block (PCB)?* *A: Keep information associated with each process* + Process state + Program counter (PC) + CPU register + CPU scheduling information + Memory-management information + Accounting information + I/O state information ### Context switch *Q: What is context?* *A: Context is saved and represented in the PCB of a process. e.g., process id, cup reg, memory areas, various tables, etc.* *Q: What is context switch?* *A: CPU switch from one process to another process.* *Q: The context is stored in a kernel data structure, what is this structure?* *A: Program counter block (abbr. PCB)* *Q: Provide a detailed description of all activates of a context switch. (= During context switch, what operations the operating system must perform?)* *A: The system must save the state (context) of the old process and load the state (context) of new process from it’s PCB.* ![](https://i.imgur.com/szfrFbH.png) ### Process Scheduling ![](https://i.imgur.com/EdPV2ys.png) + ready: waiting to be assigned to a processor + waiting: **waiting for some events to occur** + running: only one process can be running on any core ![](https://i.imgur.com/58Osw9J.png) 剩下的去看第五章 ### Operation on processes #### Process creation A process may create several new processes + The creating process is called parent + The new processes are called children of that process Execution + Parent and children execute concurrently, or + Parent waits until children terminate Address space + `fork()` Child duplicate of parent, or has the same program and data as the parent + `fork() + exec()`Child has a new program loaded into it #### Process termination + When a process terminates and before parent calls wait(), the terminated process becomes a **zombie process**. + If parent did not invoke wait() and is terminated, the child process becomes as **orphans** ### Interprocess communication (IPC) > node.js 的 IPC 套件 https://www.npmjs.com/package/node-ipc 1. Message passing (message queue) > 1. Useful for exchanging smaller amounts of data (via memory) > 2. Easier to implement > 3. Slow (due to system calls required) > 4. No conflict need to be avoided > > ```c > #include<mqueue.h> > mq_open() > mq_send() > mq_reveive() > mq_close() > ``` 2. Shared memory > 1. Faster (due to no system calls required) > 2. Need to protection and synchronization > ```c > #include<sys/mman.h> > shm_open() > mmap() > shm_unlink() > ``` ![](https://i.imgur.com/UX8R6ci.png) **↑ 左為 message passing;右為 shared memory** ### Socket & Remote procedure calls (RPC) RPC and RMI (Remote Method Invocation) are high level form of communication. Socket is low level ![](https://i.imgur.com/jpPcLbA.png) ↑ **socket (TCP)** #### RPC problems > The main challenge of RPC is to look as much like local procedure call, i.e., transparency 什麼是 transparency? Client & server may be different types of machine different data representation, e.g., big-endian vs. little-endian, ASCII, EBCDIC, 1's complement vs. 2's complement Solution. 透過 External data representation (XDR). machine independent data representation. 實作上透過一個叫 stub 的 library (A library in the client and server) + Client stub (like sender) + Locates the server + Marshal params into a msgs + Calls OS (i.e., calling socket APIs) to send msg to the server + Waits for result returned from the server + **Machine-dependent data => XDR** + Server stub (like receiver) + Be blocked waiting for incoming msg by calling receive() + Unmarshal the params + Clls the corresponding procedure in the conventioanl way + Returns result to the caller. + **XDR => Machine-dependent data** *Q: Explain the purpose of external data representation (XDR).* *A: 為了解決client和server用不同平台而導致的data representation的問題。* <style> #author{ border: 1px solid gray; border-radius: 10px; padding: 10px; width: 80%; margin: 10px auto; } </style> <div id="author"> <p>111級中興資工</p> <p>作者:<a href="https://github.com/liao2000">廖柏丞</a> </div>

    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