---
# System prepended metadata

title: 作業系統期中筆記 I - 國立中興大學大資訊工程系 Autumn 2020 CH1-3
tags: [大三]

---

---
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>