CH-1

操作系统书籍笔记

Operating Systems Book Notes


第1章:简介

Chapter 1: Introduction

1.1 什么是计算机系统?
1.1 What is a Computer System?
• 计算机系统由以下组成:
A computer system consists of:
硬件
Hardware
软件
Software

什么是操作系统?
What is an Operating System (OS)?
自上而下的视角(扩展机器):
Top-down view (Extended Machine):
◦ 隐藏复杂的硬件细节。
Hides complex hardware details.
◦ 为用户提供一个更易使用的虚拟机。
Presents a virtual machine that is easier to use.

自下而上的视角(资源管理器):
Bottom-up view (Resource Manager):
◦ 允许多个程序同时运行。
Allows multiple programs to run simultaneously.
◦ 管理和保护资源(内存、I/O设备等)。
Manages and protects resources (memory, I/O devices, etc.).
资源复用(共享):
Multiplexing (sharing) resources:
时间复用: 资源在时间上共享(例如,CPU时间片)。
In time: Resources are shared over time (e.g., CPU time slices).
空间复用: 资源在空间上共享(例如,内存分区)。
In space: Resources are shared in space (e.g., memory partitions).

操作系统历史与发展

History and Development of Operating Systems


1.2 操作系统历史

1.2 History of Operating Systems

第一代(1945 - 1955):真空管与插线板
First Generation (1945 - 1955): Vacuum Tubes and Plugboards
• 特点:
Characteristics:
◦ 使用真空管和手工操作。
Used vacuum tubes and handwork.
◦ 用户:操作员和程序员。
Users: Operators and programmers.
◦ 编程语言:机器语言。
Programming language: Machine language.
◦ 输入/输出:插线板、穿孔卡片。
I/O: Plugboards, punched cards.
◦ 用户独占机器,CPU等待用户加载和卸载插线板。
The user occupied the machine alone; CPU waited for the user to load and unload the plugboard.
◦ 矛盾:CPU高速与手工操作低速的冲突。
Conflict: High-speed CPU vs. low-speed handwork.
◦ 解决方法:引入专门的操作员和批处理系统。
Solution: Introduced special operators and batch systems.

插线板(Plugboard)
◦ 整个计算机是一个巨大的插线板,通过插入线路实现不同功能。
The entire computer was a large plugboard; inserting wires in different positions achieved different functions.

穿孔卡片(Punched Card)
◦ 穿孔卡片是一种纸卡片,IBM的12行80列穿孔卡片曾是主流。
Punched cards were paper cards; IBM's 12-row, 80-column punched cards were once mainstream.


第二代(1955 - 1965):晶体管与批处理系统
Second Generation (1955 - 1965): Transistors and Batch Systems
• 特点:
Characteristics:
◦ 使用晶体管。
Used transistors.
◦ 用户:操作员或程序员。
Users: Operators or programmers.
◦ 编程语言:汇编语言、Fortran等。
Programming languages: Assembly language, Fortran, etc.
◦ 输入/输出:卡片、磁带。
I/O: Cards, tapes.
◦ 操作系统:监控程序(执行作业)。
OS: Monitor (executed jobs).
◦ 批处理系统:在线批处理系统 / 离线批处理系统。
Batch systems: Online batch system / Offline batch system.

早期离线批处理系统
Early Offline Batch System
◦ (a) 程序员将卡片带到1401机。
(a) Programmers brought cards to the 1401.
◦ (b) 1401将一批作业读取到磁带上。
(b) 1401 read a batch of jobs onto tape.
◦ (c) 操作员将输入磁带带到7094机。
(c) Operator carried input tape to the 7094.
◦ (d) 7094进行计算。
(d) 7094 did computing.
◦ (e) 操作员将输出磁带带回1401机。
(e) Operator carried output tape back to the 1401.
◦ (f) 1401打印输出。
(f) 1401 printed output.

典型FMS作业结构(第二代)
Structure of a Typical FMS Job – 2nd Generation
◦ 作业:程序、数据、作业说明。
Job: Program, data, job specification.


第三代(1965 - 1980):集成电路与多道程序设计
Third Generation (1965 - 1980): ICs and Multiprogramming
• 特点:
Characteristics:
◦ 使用集成电路(IC)。
Used Integrated Circuits (ICs).
◦ 批处理系统:效率高,但交互性差。
Batch systems: High efficiency, poor interaction.
◦ 分时系统(多道程序设计的变体):
Time-sharing system (a variant of multiprogramming):
◦ 多个用户共享计算机,每个用户有一个在线终端。
Multiple users shared the computer; each had an online terminal.
◦ 按时间片分配CPU。
Allocated CPU by time slice.
◦ 快速响应时间。
Quick response time.

多道程序设计系统
Multiprogramming System
◦ 将内存划分为多个分区,每个分区运行一个作业。
Partitioned memory into several pieces, with a different job in each partition.
◦ 宏观上并行,微观上串行。
Parallel in macroscopic, serial in microcosmic.


第四代(1980 - 至今):个人计算机与工作站
Fourth Generation (1980 – Present): Personal Computers and Workstations
• 特点:
Characteristics:
◦ 大规模集成电路(LSI)。
Large Scale Integration (LSI).
◦ 个人计算机操作系统:
Operating systems for personal computers:
◦ CP/M(微型计算机控制程序)。
CP/M (Control Program for Microcomputers).
◦ DOS(磁盘操作系统)➔ MS-DOS。
DOS (Disk Operating System) ➔ MS-DOS.
◦ 图形用户界面(GUI)。
Graphical User Interface (GUI).
◦ Windows ➔ Windows 95/98/Me ➔ Windows NT ➔ Windows 2000 ➔ Windows XP ➔ Vista ➔ Win7 ➔ Win8 ➔ Win10 ➔ Win11。
◦ UNIX:
▪ X Windows。
▪ Linux, GNOME, KDE。


第五代(1990 - 至今):智能手机与移动操作系统
Fifth Generation (1990 – Present): Smartphones and Mobile Operating Systems
• 特点:
Characteristics:
◦ 1970年代开始将电话与计算结合。
Combining telephony and computing since the 1970s.
◦ 第一款真正的智能手机:诺基亚N9000(1990年代中期)。
The first real smartphone: Nokia N9000, mid-1990s.
◦ Symbian OS。
◦ RIM的Blackberry OS(2002年推出)。
RIM’s Blackberry OS introduced in 2002.
◦ 苹果的iOS(2007年随第一代iPhone发布)。
Apple’s iOS released for the first iPhone in 2007.
◦ 谷歌的Android(2008年发布)。
Google’s Android in 2008.


国产操作系统的发展

Development of Domestic Operating Systems

• 国产操作系统多为以Linux为基础二次开发的操作系统。
Most domestic operating systems are based on Linux and developed further.
• 红旗Linux
Red Flag Linux
• 普华Linux(i-soft)
Puhua Linux (i-soft)
• 中兴新支点操作系统
ZTE’s NewStart OS
• 威科乐恩Linux(WiOS)
Wecolon Linux (WiOS)
• 安超OS(国产通用型云OS)
Anchao OS (Domestic General Cloud OS)
• 起点操作系统(StartOS)
StartOS
• 凝思磐石安全操作系统
Ningsi Rocksolid Security OS
• 一铭操作系统(YMOS)
Yiming OS (YMOS)
• 深度Linux(Deepin)
Deepin Linux
• 统信操作系统UOS
Tongxin OS (UOS)
• 银河麒麟、中标麒麟(Kylin)
Galaxy Kirin, NeoKylin (Kylin)
• 华为鸿蒙操作系统(HarmonyOS)
Huawei’s HarmonyOS
• 华为欧拉操作系统(EulerOS)
Huawei’s EulerOS

1.4 操作系统动物园

1.4 The Operating System Zoo


1. 大型机操作系统

1. Mainframe Operating Systems
• 特点:
Characteristics:
• 用于大型计算机,通常用于处理大规模数据处理任务。
Used for mainframe computers, typically for large-scale data processing tasks.
• 示例:
Examples:
• OS/390
• zOS


2. 服务器操作系统

2. Server Operating Systems
• 特点:
Characteristics:
• 用于服务器,支持多用户和多任务处理。
Used for servers, supporting multi-user and multi-tasking environments.
• 示例:
Examples:
• Solaris
• FreeBSD
• Linux
• Windows Server 201x


3. 多处理器操作系统

3. Multiprocessor Operating Systems
• 特点:
Characteristics:
• 支持多处理器系统,充分利用多核CPU的性能。
Supports multiprocessor systems, fully utilizing the performance of multi-core CPUs.


4. 个人计算机操作系统

4. Personal Computer Operating Systems
• 特点:
Characteristics:
• 用于个人计算机,提供用户友好的界面和应用程序支持。
Used for personal computers, providing user-friendly interfaces and application support.
• 示例:
Examples:
• Windows 7/8/10/11
• Linux
• FreeBSD
• Apple macOS


5. 手持设备操作系统

5. Handheld Operating Systems
• 特点:
Characteristics:
• 用于智能手机、平板电脑等移动设备,支持触控和移动应用。
Used for smartphones, tablets, and other mobile devices, supporting touch and mobile applications.
• 示例:
Examples:
• Android
• iOS


6. 嵌入式操作系统

6. Embedded Operating Systems
• 特点:
Characteristics:
• 用于嵌入式设备,如家电、汽车、工业设备等,通常资源受限。
Used for embedded devices such as appliances, cars, and industrial equipment, typically with limited resources.
• 示例:
Examples:
• QNX
• VxWorks


7. 传感器节点操作系统

7. Sensor Node Operating Systems
• 特点:
Characteristics:
• 用于无线传感器网络,通常资源非常有限。
Used for wireless sensor networks, typically with very limited resources.
• 示例:
Examples:
• TinyOS


8. 实时操作系统

8. Real-Time Operating Systems
• 特点:
Characteristics:
• 用于实时系统,任务必须在严格的时间限制内完成。
Used for real-time systems, where tasks must be completed within strict time constraints.
硬实时系统(Hard Real-Time System): 动作必须在特定时刻发生。
Hard Real-Time System: The action absolutely must occur at a certain moment.
• 示例:
Examples:
◦ e-Cos


9. 智能卡操作系统

9. Smart Card Operating Systems
• 特点:
Characteristics:
• 用于智能卡,通常运行在资源极其有限的环境中。
Used for smart cards, typically running in extremely resource-constrained environments.
• 示例:
Examples:
• Java虚拟机(JVM)
Java Virtual Machine (JVM)


总结

Summary

操作系统的种类繁多,适用于不同的计算环境和设备类型:
There are many types of operating systems, suitable for different computing environments and device types:
• 大型机操作系统:用于大规模数据处理。
Mainframe OS: For large-scale data processing.
• 服务器操作系统:支持多用户和多任务。
Server OS: Supports multi-user and multi-tasking.
• 个人计算机操作系统:提供用户友好的界面。
PC OS: Provides user-friendly interfaces.
• 手持设备操作系统:支持移动应用和触控。
Handheld OS: Supports mobile applications and touch.
• 嵌入式操作系统:用于资源受限的嵌入式设备。
Embedded OS: For resource-constrained embedded devices.
• 实时操作系统:用于严格时间限制的任务。
Real-Time OS: For tasks with strict time constraints.
• 智能卡操作系统:用于智能卡等小型设备。
Smart Card OS: For small devices like smart cards.

每种操作系统都有其独特的应用场景和设计目标。
Each type of operating system has its unique application scenarios and design goals.

1.5 操作系统概念

1.5 Operating System Concepts


进程(Processes)

进程的定义:
Definition of a Process:
• 进程是正在执行的程序。
A process is a program in execution.

进程控制块(PCB):
Process Control Block (PCB):
• 为了描述和控制进程的运行,系统为每个进程定义了一个数据结构——进程控制块(PCB)。
To describe and control the execution of a process, the system defines a data structure for each process called the Process Control Block (PCB).
• 系统创建一个进程,就是为某个程序设置一个PCB,用于对该进程进行控制和管理。
When the system creates a process, it sets up a PCB for the program to control and manage the process.
• 进程任务完成后,系统收回其PCB,该进程便消亡。
When the process completes its task, the system reclaims its PCB, and the process terminates.
• PCB是进程存在的唯一标志。
The PCB is the only identifier of a process’s existence.

进程表(Process Table):
Process Table:
• 进程信息(PCB)存储在操作系统的进程表中。
The information about a process (PCB) is stored in an operating system table called the process table.

命令解释器(Shell):
Command Interpreter (Shell):
• 一个称为命令解释器或shell的进程从终端读取命令。
A process called the command interpreter or shell reads commands from a terminal.

进程树(Process Tree):
Process Tree:
• 如果一个进程可以创建一个或多个其他进程(子进程),并且这些进程也可以创建子进程,那么它们可以构建成一个树结构。
If a process can create one or more other processes (child processes) and these processes create child processes, we can build them in a tree structure.
• 在UNIX中,所有进程都有一个父进程。
In UNIX, there is a parent process for all processes.

img

进程状态:
Process Status:
• 进程有多种状态:运行(running)、阻塞(blocked)、就绪(ready)。
Processes have many statuses: running, blocked, ready.

用户与进程标识:
User and Process Identification:
• 每个授权使用系统的用户被分配一个用户标识符(UID)。
Each person authorized to use a system is assigned a UID (User IDentification).
• 进程被分配一个进程标识符(PID)。
A process is assigned a PID (Process IDentification).
• 用户可以属于组,每个组有一个组标识符(GID)。
Users can be members of groups, each of which has a GID (Group IDentification).
• 超级用户(UNIX中的root)有特殊权限,可以违反许多保护规则。
The superuser (root in UNIX) has special privileges to violate many of the protection rules.

进程间通信(IPC):
Interprocess Communication (IPC):
• 进程之间用于协作和同步的通信称为进程间通信。
The communication to cooperate and synchronize processes is called interprocess communication.


地址空间与文件(Address Spaces & Files)

地址空间:
Address Space:
• 地址空间是从0到某个最大值的内存分配列表,进程可以读写这些内存。
Address Space: a list of memory allocations from 0 to some maximum, which the process can read and write.
• 在虚拟内存中,操作系统将部分地址空间保留在主存中,部分保留在磁盘上。
In virtual memory, the operating system keeps part of the address space in main memory and part on disk.

文件系统:
File System:
• 文件系统为用户提供了一个干净、设备独立的文件抽象模型。
A file system provides users with a nice, clean abstract model of device-independent files.
• 目录用于将文件分组。
A directory is used to group files together.
• 路径名可以指定文件的位置。
A path name can specify the location of a file.
• 根目录是目录层次结构的顶部。在UNIX中,/是根目录。
A root directory is the top of the directory hierarchy. In UNIX, / is the root directory.
• 每个进程都有一个当前工作目录(pwd)。
Each process has a current working directory (pwd).

img

文件描述符:
File Descriptor:
• 如果允许访问文件,系统会返回一个称为文件描述符的小整数,用于后续操作。
If a file access is permitted, the system returns a small integer called a file descriptor to use in subsequent operations.

特殊文件:
Special Files:
• UNIX中有两种特殊文件:块特殊文件(磁盘)和字符特殊文件(打印机、调制解调器)。
Two kinds of special files exist in UNIX under the /dev directory: block special files (disks) and character special files (printers, modems).

挂载文件系统:
Mounted File System:
• 在UNIX中,挂载文件系统用于处理可移动介质(如CD-ROM)。
In UNIX, the mounted file system is used to deal with removable media (mount).
• 挂载前,CD-ROM上的文件不可访问。
Before mounting, the files on the CD-ROM are not accessible.
• 挂载后,CD-ROM上的文件成为文件层次结构的一部分。
After mounting, the files on the CD-ROM are part of the file hierarchy.

img

管道(Pipe):
Pipe:
• 管道是一种伪文件,用于连接两个进程。
A pipe is a sort of pseudofile that can be used to connect two processes.

img

输入/输出(Input/Output)

I/O子系统:
I/O Subsystem:
• 操作系统必须能够与多种外设(键盘、鼠标、显示器、打印机等)通信。
OS must understand how to communicate with many types of peripherals (keyboard, mouse, monitor, printer, etc.).
• 每个操作系统都有一个I/O子系统来管理其I/O设备。
Every OS has an I/O sub-system for managing its I/O devices.

Some of the I/O software is device independent. Other parts of it, such as device drivers, are specific to particular I/O devices.


中文翻译:

有些 I/O 软件是设备无关的(device independent)。 另一些部分,例如设备驱动程序(device drivers),则是针对特定 I/O 设备编写的

设备驱动程序:
Device Driver:
• 设备驱动程序是黑盒,用于隐藏硬件设备的细节。
Device drivers are black boxes to hide details of hardware devices.
• 主要作用:将标准调用映射到设备特定的操作。
Main Role: Map standard calls to device-specific operations.
• 可以与内核的其他部分分开开发,并在需要时在运行时插入。
Can be developed separately from the rest of the kernel. Plugged in at runtime when needed.


保护(Protection)

保护机制:
Protection Mechanism:
• 操作系统必须防止对资源的未授权访问。
OS must prevent unauthorized access to resources.
• 还必须防止一个用户干扰另一个用户的资源(如文件)。
Must also prevent one user from interfering with another user’s resources (e.g., files).

UNIX文件保护:
UNIX File Protection:
• UNIX中的文件通过一个9位二进制保护代码进行保护。
Files in UNIX are protected by a 9-bit binary protection code.
• 保护代码由三个3位字段组成,分别用于所有者、组和其他人。
The protection code consists of three 3-bit fields, one for owner, one for group, and one for others.
• 每个字段有一个读位、一个写位和一个执行位,称为rwx位。
Each field has a bit for read, a bit for write, and a bit for execute. They are known as rwx bits.


Shell

UNIX Shell:
UNIX Shell:
• UNIX命令解释器称为shell。
The UNIX command interpreter is called the shell.
• 三种主要的UNIX Shell:
Three Major Unix Shells:
Bourne Shell(标准Shell): sh, bash,命令提示符为$
Bourne Shell (or Standard Shell): sh, bash. $ for command prompt.
Korn Shell: ksh,是sh的超集。
Korn shell: ksh. Superset of sh.
C Shell: 语法类似C语言,命令提示符为%
C Shell: Shell with C-like syntax. % for command prompt.

输入/输出重定向:
Input/Output Redirection:
• 用户可以使用<>重定向标准输入和输出。
The user can use < and > to redirect the standard input and output.
• 在命令后添加&可以将其作为后台作业启动。
The ampersand (&) can be put after a command to start it as a background job.
• 示例:
Examples:
date >file:将日期输出到文件。
sort <file1 >file2:对file1排序并输出到file2。
cat file1 file2 file3 | sort >/dev/lp:将多个文件合并、排序并输出到打印机。
cat file1 file2 file3 | sort >/dev/lp &:将上述操作作为后台作业运行。


总结

Summary

操作系统核心概念包括:
The core concepts of operating systems include:
进程: 程序执行的实例,通过PCB管理。
Processes: Instances of program execution, managed via PCBs.
地址空间与文件: 内存管理和文件系统抽象。
Address Spaces & Files: Memory management and file system abstraction.
输入/输出: 设备驱动程序和I/O子系统。
Input/Output: Device drivers and I/O subsystems.
保护: 防止未授权访问和用户干扰。
Protection: Preventing unauthorized access and user interference.
Shell: 命令解释器,支持输入/输出重定向和后台作业。
Shell: Command interpreter, supporting I/O redirection and background jobs.

这些概念共同构成了操作系统的基础功能。
These concepts together form the foundational functions of an operating system.

1.6 系统调用

1.6 System Calls


系统调用的定义与作用

Definition and Role of System Calls

系统调用:
System Calls:
• 提供了运行程序与操作系统之间的接口。
Provide the interface between a running program and the operating system.
• 应用程序通过系统调用向操作系统请求服务。
The mechanism used by an application program to request service from the operating system.
• 通常通过高级应用程序编程接口(API)访问,而不是直接使用系统调用。
Mostly accessed by programs via a high-level Application Programming Interface (API) rather than direct system call use.

常见的API:
Common APIs:
Win32 API: 用于Windows。
Win32 API for Windows.
POSIX API: 用于基于POSIX的系统(包括几乎所有UNIX、Linux和macOS版本)。
POSIX API for POSIX-based systems (including virtually all versions of UNIX, Linux, and Mac OS X).
Java API: 用于Java虚拟机(JVM)。
Java API for the Java virtual machine (JVM).


POSIX标准

POSIX Standard

POSIX(可移植操作系统接口):
POSIX (Portable Operating System Interface):
• 一组IEEE标准,包括强制和可选部分。
Set of IEEE standards, including mandatory and optional parts.
• 目标:实现应用程序在多个操作系统之间的源代码可移植性。
Objective: Source code portability of applications across multiple OS.
• 大多数POSIX过程调用系统调用,通常一个过程直接映射到一个系统调用,但并不绝对一一对应。
Most of the POSIX procedures invoke system calls, usually with one procedure mapping directly onto one system call. But it is not absolutely one-to-one.


系统调用的执行步骤

Steps in Making a System Call

系统调用的11个步骤(以read为例):
11 Steps in Making the System Call read(fd, buffer, nbytes):

1. 用户程序调用库函数`read`。  
   **User program calls the library procedure `read`.**  
2. 将`nbytes`压入栈。  
   **Push `nbytes`.**  
3. 将`&buffer`压入栈。  
   **Push `&buffer`.**  
4. 将`fd`压入栈。  
   **Push `fd`.**  
5. 调用`read`函数。  
   **Call `read`.**  
6. 增加栈指针(SP)。  
   **Increment SP.**  
7. 将`read`的系统调用代码放入寄存器。  
   **Put code for `read` in register.**  
8. 陷入内核(Trap to the kernel)。  
   **Trap to the kernel.**  
9. 内核调用系统调用处理程序。  
   **Kernel calls the system call handler.**  
10. 调度执行系统调用服务例程。  
    **Dispatch to the system call service routine.**  
11. 返回调用者。  
    **Return to the caller.**  

用户态与内核态切换:
User Mode and Kernel Mode Switching:
• 用户程序通过int 0x80指令陷入内核态,执行系统调用例程。
User program traps to kernel mode via int 0x80 to execute the system call routine.
• 系统调用完成后,通过iret指令返回到用户态。
After the system call completes, return to user mode via iret.


系统调用代码示例

System Call Code Example

Linux系统调用代码(部分):
Linux System Call Codes (Partial):

1
2
3
4
5
6
7
8
#define __NR_restart_syscall 0
#define __NR_exit 1
#define __NR_fork 2
#define __NR_read 3
#define __NR_write 4
#define __NR_open 5
#define __NR_close 6
#define __NR_waitpid 7


进程管理的系统调用

System Calls for Process Management

创建进程:
Creating a Process:
fork() 创建与父进程完全相同的子进程。
fork(): Create a child process identical to the parent.
◦ 该函数调用一次但返回两次:在子进程中返回0,在父进程中返回子进程的PID,出错时返回-1。
This function is called once but returns twice: 0 in the child, process ID of the child in the parent, -1 on error.
◦ 子进程和父进程都从fork调用后的指令继续执行。
Both the child and parent continue executing with the instruction that follows the call to fork.

替换进程内存空间:
Replacing Process Memory Space:
execve()fork之后使用,用新程序替换进程的内存空间。
execve(): Used after fork to replace the process’ memory space with a new program.
◦ 允许子进程执行与父进程不同的代码。
Allows the child process to execute code that is different from that of the parent.
exec函数族:execl, execle, execlp, execv, execve, execvp
exec family of functions: execl, execle, execlp, execv, execve, execvp.

等待子进程终止:
Waiting for Child Process Termination:
waitpid() 将父进程移出就绪队列,直到子进程终止。
waitpid(): Moves the parent process off the ready queue until the termination of the child.
◦ 返回值:成功时返回子进程的PID,出错时返回0或-1。
Return: Process ID if OK, 0 or –1 on error.
pid参数的解释:
Interpretation of the pid argument:
pid == -1:等待任何子进程(等同于wait)。
pid == -1: Waits for any child process (equivalent to wait).
pid > 0:等待进程ID等于pid的子进程。
pid > 0: Waits for the child whose process ID equals pid.


简单的Shell实现

A Simple Shell Implementation

代码示例:
Code Example:

1
2
3
4
5
6
7
8
9
10
11
#define TRUE 1

while (TRUE) {
type_prompt(); // 显示提示符
read_command(command, parameters); // 从终端读取输入
if (fork() != 0) { // 创建子进程
waitpid(-1, &status, 0); // 父进程等待子进程终止
} else {
execve(command, parameters, 0); // 子进程执行命令
}
}


总结

Summary

系统调用是操作系统与应用程序之间的桥梁,提供了对底层硬件和系统资源的安全访问。
System calls are the bridge between the operating system and applications, providing secure access to underlying hardware and system resources.
进程管理: 通过forkexecvewaitpid等系统调用实现进程的创建、替换和同步。
Process Management: Processes are created, replaced, and synchronized via system calls like fork, execve, and waitpid.
系统调用执行: 涉及用户态与内核态的切换,通常通过高级API(如POSIX)访问。
System Call Execution: Involves switching between user mode and kernel mode, usually accessed via high-level APIs like POSIX.
Shell实现: 通过系统调用实现简单的命令解释器。
Shell Implementation: A simple command interpreter can be implemented using system calls.

1.6 系统调用(续)

1.6 System Calls (Continued)


进程创建示例:fork

Example of Process Creation: fork

代码示例:
Code Example:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <unistd.h>

int main() {
int i, pid;
for (i = 1; i <= 3; i++) {
if ((pid = fork()) == 0) {
printf("In child %d.\n", i);
}
}
return 0;
}

功能: 创建3个子进程,每个子进程打印自己的编号。
Function: Creates 3 child processes, each printing its own number.
说明: fork()调用一次返回两次,父进程和子进程分别执行后续代码。
Note: fork() is called once but returns twice; the parent and child processes execute the subsequent code separately.

img

文件管理的系统调用

System Calls for File Management

常见文件管理系统调用:
Common File Management System Calls:

调用 描述
fd = open(file, how, ...) 打开文件用于读取、写入或两者。
Open a file for reading, writing, or both.
s = close(fd) 关闭一个已打开的文件。
Close an open file.
n = read(fd, buffer, nbytes) 从文件中读取数据到缓冲区。
Read data from a file into a buffer.
n = write(fd, buffer, nbytes) 将缓冲区中的数据写入文件。
Write data from a buffer into a file.
position = lseek(fd, offset, whence) 移动文件指针。
Move the file pointer.
s = stat(name, &buf) 获取文件的状态信息。
Get a file's status information.

目录管理的系统调用

System Calls for Directory Management

常见目录管理系统调用:
Common Directory Management System Calls:

调用 描述
s = mkdir(name, mode) 创建一个新目录。
Create a new directory.
s = rmdir(name) 删除一个空目录。
Remove an empty directory.
s = link(name1, name2) 创建一个新条目name2,指向name1
Create a new entry, name2, pointing to name1.
s = unlink(name) 删除一个目录条目。
Remove a directory entry.
s = mount(special, name, flag) 挂载一个文件系统。
Mount a file system.
s = umount(special) 卸载一个文件系统。
Unmount a file system.

链接(Linking)

Linking

示例:
Example:

1
link("/usr/jim/memo", "/usr/ast/note");

功能:/usr/ast目录中创建一个新条目note,指向/usr/jim/memo
Function: Creates a new entry note in /usr/ast, pointing to /usr/jim/memo.
图示:
(a) 链接前的目录结构。
(a) Directory structure before linking.
(b) 链接后的目录结构。
(b) Directory structure after linking.

img

挂载(Mounting)

Mounting

示例:
Example:

1
mount("/dev/fd0", "/mnt", 0);

功能: 将设备/dev/fd0挂载到目录/mnt
Function: Mounts the device /dev/fd0 to the directory /mnt.
图示:
(a) 挂载前的文件系统。
(a) File system before the mount.
(b) 挂载后的文件系统。
(b) File system after the mount.

img

其他任务的系统调用

System Calls for Miscellaneous Tasks

示例:
Examples:
更改当前目录:
Change current directory:

1
chdir("/usr/ast/test");
更改文件权限:
Change file permissions:
1
2
chmod("file", 0644);  // 使文件对除所有者外的所有用户只读。  
// Makes the file read-only by everyone except the owner.


Win32 API中的系统调用

System Calls in Win32 API

特点:
Characteristics:
• 在Windows中,库调用和实际系统调用高度解耦。
In Windows, the library calls and the actual system calls are highly decoupled.
• Win32 API为程序员提供了访问操作系统服务的接口。
Win32 API provides programmers with an interface to access OS services.
• Win32 API调用的数量非常庞大,多达数千个。
The number of Win32 API calls is extremely large, numbering in the thousands.
• 虽然许多Win32 API会调用系统调用,但也有大量调用完全在用户空间执行。
While many of Win32 APIs do invoke system calls, a substantial number are carried out entirely in user space.


总结

Summary

系统调用是操作系统功能的核心,涵盖了进程管理、文件管理、目录管理等多个方面。
System calls are the core of operating system functionality, covering process management, file management, directory management, and more.
进程管理: 通过forkexecvewaitpid等调用实现进程的创建和同步。
Process Management: Processes are created and synchronized via calls like fork, execve, and waitpid.
文件与目录管理: 通过openreadmkdir等调用实现文件和目录的操作。
File and Directory Management: Files and directories are manipulated via calls like open, read, and mkdir.
Win32 API: 提供了丰富的系统调用接口,但部分调用在用户空间执行。
Win32 API: Provides a rich interface for system calls, but some calls are executed entirely in user space.

1.7 操作系统结构

1.7 Operating System Structure


1. 单体系统(Monolithic System)

Monolithic System

特点:
Characteristics:
• 也称为“大杂烩”,所有操作系统功能都放在一个文件中。
Also known as "the big mess," all operating system operations are put into a single file.
• 操作系统是一组过程,每个过程可以调用其他过程。
The operating system is a collection of procedures, each of which can call any of the others.

基本结构:
Basic Structure:

1. **主程序:** 调用所需的服务过程。  
   **Main program:** Invokes the requested service procedure.  
2. **服务过程:** 执行系统调用。  
   **Service procedures:** Carry out the system calls.  
3. **实用过程:** 帮助服务过程完成任务。  
   **Utility procedures:** Help the service procedures.  

优点:
Advantages:
• 简单直接,性能高。
Simple and straightforward, high performance.

缺点:
Disadvantages:
• 难以维护和扩展,容易出现错误。
Difficult to maintain and extend, prone to errors.

image-20250506000142418

2. 分层系统(Layered System)

Layered System

特点:
Characteristics:
• 操作系统被组织为层次结构,每一层构建在下一层之上。
The operating system is organized as a hierarchy of layers, each one constructed upon the one below it.

示例:
Example:
THE操作系统(Dijkstra, 1968): 第一个分层系统。
THE Operating System (Dijkstra, 1968): The first layered system.

优点:
Advantages:
• 结构清晰,易于调试和维护。
Clear structure, easy to debug and maintain.

缺点:
Disadvantages:
• 层与层之间的通信可能影响性能。
Communication between layers may affect performance.


3. 微内核(Microkernel)

Microkernel

特点:
Characteristics:
• 将尽可能多的功能从内核移到用户空间。
Move as much functionality as possible from the kernel into user space.
• 内核非常小,仅提供最基本的功能:
OS kernel is very small – minimal functionality:
◦ 原始内存管理(地址空间)。
Primitive memory management (address space).
◦ I/O和中断管理。
I/O and interrupt management.
◦ 进程间通信(IPC)。
Inter-Process Communication (IPC).
◦ 基本调度。
Basic scheduling.

其他功能:
Other Functions:
• 其他操作系统功能由用户空间的受信任服务器提供。
Other OS functions provided at user level by trusted servers.
• 例如:设备驱动程序、文件系统、虚拟内存等。
E.g., Device drivers, file system, virtual memory, etc.

示例:
Example:
MINIX 3系统: 典型的微内核结构。
MINIX 3 system: A typical microkernel structure.

优点:
Advantages:
• 内核小巧,易于扩展和维护。
Small kernel, easy to extend and maintain.
• 提高系统的稳定性和安全性。
Improves system stability and security.

缺点:
Disadvantages:
• 用户空间和内核空间之间的通信开销较大。
High communication overhead between user space and kernel space.


4. 客户端-服务器模型(Client-Server Model)

Client-Server Model

特点:
Characteristics:
• 微内核的变体,区分两类进程:服务器和客户端。
A slight variation of microkernel, distinguishing two classes of processes: servers and clients.
• 将大部分代码移到高层,使内核最小化,仅负责客户端和服务器之间的通信。
Moving most of the code up into the higher layers made the kernel minimal and only responsible for communication between clients and servers.

网络环境:
Over a Network:
• 客户端和服务器可以运行在不同的计算机上,通过局域网或广域网连接。
The clients and servers run on different computers, connected by a local or wide-area network.

优点:
Advantages:
• 分布式处理,提高系统的可扩展性和灵活性。
Distributed processing, improves scalability and flexibility.

缺点:
Disadvantages:
• 网络通信可能引入延迟和复杂性。
Network communication may introduce latency and complexity.


5. 虚拟机(Virtual Machines)

Virtual Machines

特点:
Characteristics:
• 虚拟机是硬件上的虚拟软件层。
Virtual software layer over hardware.
• 模拟抽象机器的软件,提供多个硬件实例的幻觉。
Software emulation of an abstract machine, illusion of multiple instances of hardware.
• 支持多个操作系统的实例。
Supports multiple instances of OSs.

示例:
Example:
VM/370 with CMS: 典型的虚拟机结构。
VM/370 with CMS: A typical virtual machine structure.

虚拟机监控程序(Hypervisor):
Hypervisor:

1. **类型1:** 直接运行在硬件上,像一个操作系统。  
   **Type 1:** Runs on the raw hardware, like an operating system.  
2. **类型2:** 运行在主机操作系统上。  
   **Type 2:** Runs on the host OS.  

优点:
Advantages:
• 提供隔离性,支持多操作系统环境。
Provides isolation, supports multiple OS environments.

缺点:
Disadvantages:
• 性能开销较大,管理复杂。
High performance overhead, complex management.


6. 外核(Exokernel)

Exokernel

特点:
Characteristics:
• 外核将硬件资源直接暴露给应用程序,由应用程序管理资源。
Exokernel exposes hardware resources directly to applications, which manage the resources themselves.
• 内核仅负责资源分配和保护。
The kernel is only responsible for resource allocation and protection.

优点:
Advantages:
• 提供更高的灵活性和性能优化空间。
Provides higher flexibility and performance optimization potential.

缺点:
Disadvantages:
• 应用程序需要承担更多管理责任,开发难度较大。
Applications need to take on more management responsibilities, increasing development complexity.


总结

Summary

操作系统的结构设计直接影响其性能、可维护性和扩展性。
The structure of an operating system directly affects its performance, maintainability, and scalability.
单体系统: 简单高效,但难以维护。
Monolithic System: Simple and efficient, but difficult to maintain.
分层系统: 结构清晰,但性能可能受限。
Layered System: Clear structure, but performance may be limited.
微内核: 内核小巧,易于扩展,但通信开销大。
Microkernel: Small kernel, easy to extend, but high communication overhead.
客户端-服务器模型: 分布式处理,提高灵活性,但网络通信复杂。
Client-Server Model: Distributed processing, improves flexibility, but network communication is complex.
虚拟机: 提供隔离性,支持多操作系统,但性能开销大。
Virtual Machines: Provides isolation, supports multiple OSs, but high performance overhead.
外核: 提供高灵活性,但开发难度大。
Exokernel: Provides high flexibility, but development is challenging.**

总结

Summary


1. 操作系统的两种视角

Two Viewpoints of OS

  1. 资源管理器(Resource Manager):
    • 操作系统负责管理和分配系统资源(如CPU、内存、I/O设备等)。
    OS manages and allocates system resources (e.g., CPU, memory, I/O devices).

  2. 扩展机器(Extended Machine):
    • 操作系统隐藏硬件的复杂性,为用户提供一个更易使用的抽象接口。
    OS hides the complexity of hardware and provides users with an easier-to-use abstract interface.


2. 操作系统的发展历史

History of OS

手工操作(Handwork):
• 早期计算机需要人工操作,效率低下。
Early computers required manual operation, which was inefficient.

批处理系统(Batch Systems):
• 通过批处理作业提高效率,但缺乏交互性。
Improved efficiency through batch processing, but lacked interactivity.

多道程序设计系统(Multiprogramming Systems):
• 允许多个程序同时运行,提高资源利用率。
Allowed multiple programs to run simultaneously, improving resource utilization.

个人计算机系统(Personal Computer Systems):
• 操作系统为个人用户提供友好的界面和应用程序支持。
OS provided user-friendly interfaces and application support for individual users.

移动计算机系统(Mobile Computer Systems):
• 操作系统为智能手机和平板电脑等移动设备优化。
OS optimized for mobile devices such as smartphones and tablets.


3. 计算机硬件

Computer Hardware

• 操作系统直接管理硬件资源,包括CPU、内存、存储设备和I/O设备。
OS directly manages hardware resources, including CPU, memory, storage devices, and I/O devices.


4. 操作系统动物园

The Operating System Zoo

• 操作系统的种类繁多,适用于不同的计算环境和设备类型,包括:
There are many types of operating systems, suitable for different computing environments and device types, including:
• 大型机操作系统(Mainframe OS)
• 服务器操作系统(Server OS)
• 个人计算机操作系统(PC OS)
• 手持设备操作系统(Handheld OS)
• 嵌入式操作系统(Embedded OS)
• 实时操作系统(Real-Time OS)
• 智能卡操作系统(Smart Card OS)


5. 操作系统核心概念

Operating System Concepts

进程(Processes):
• 程序执行的实例,通过进程控制块(PCB)管理。
Instances of program execution, managed via Process Control Blocks (PCBs).

地址空间(Address Space):
• 进程可以访问的内存范围,包括虚拟内存管理。
The range of memory a process can access, including virtual memory management.

文件(Files):
• 文件系统提供对存储设备上文件的抽象和管理。
File systems provide abstraction and management of files on storage devices.

保护(Protection):
• 防止未授权访问和用户之间的干扰。
Prevents unauthorized access and interference between users.

Shell:
• 命令解释器,提供用户与操作系统之间的交互接口。
Command interpreter, providing an interface between users and the OS.


6. 系统调用

System Calls

• 系统调用是应用程序与操作系统之间的接口,用于请求服务。
System calls provide the interface between application programs and the OS, used to request services.
• 常见的系统调用包括:
Common system calls include:
• 进程管理(fork, execve, waitpid
• 文件管理(open, read, write, close
• 目录管理(mkdir, rmdir, link
• 其他任务(chdir, chmod


7. 操作系统结构

OS Structure

单体系统(Monolithic System):
• 所有功能集中在一个内核中,简单高效但难以维护。
All functions are centralized in a single kernel, simple and efficient but difficult to maintain.

分层系统(Layered System):
• 操作系统按层次组织,结构清晰但性能可能受限。
OS is organized in layers, clear structure but performance may be limited.

微内核(Microkernel):
• 内核小巧,大部分功能在用户空间运行,易于扩展但通信开销大。
Small kernel, most functions run in user space, easy to extend but high communication overhead.

客户端-服务器模型(Client-Server Model):
• 将功能分布到客户端和服务器进程中,提高灵活性但网络通信复杂。
Distributes functions to client and server processes, improves flexibility but network communication is complex.

虚拟机(Virtual Machines):
• 提供硬件虚拟化,支持多操作系统实例,但性能开销大。
Provides hardware virtualization, supports multiple OS instances, but high performance overhead.

外核(Exokernel):
• 将硬件资源直接暴露给应用程序,提供高灵活性但开发难度大。
Exposes hardware resources directly to applications, provides high flexibility but development is challenging.


最终总结

Final Summary

操作系统是计算机系统的核心,负责管理硬件资源、提供用户接口和支持应用程序运行。
The operating system is the core of a computer system, responsible for managing hardware resources, providing user interfaces, and supporting application execution.
通过不同的结构设计和功能实现,操作系统能够适应各种计算环境和需求。
Through different structural designs and functional implementations, operating systems can adapt to various computing environments and needs.