+ All Categories
Home > Documents > Chapter 4: Processes

Chapter 4: Processes

Date post: 16-Jan-2016
Category:
Upload: xanti
View: 23 times
Download: 0 times
Share this document with a friend
Description:
Chapter 4: Processes. Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems. Process Concept. An operating system executes a variety of programs: Batch system – jobs( 作业) - PowerPoint PPT Presentation
47
Chapter four 4.1 Operating System Concepts Chapter 4: Processes Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems
Transcript
Page 1: Chapter 4:  Processes

Chapter four 4.1 Operating System Concepts

Chapter 4: Processes

Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems

Page 2: Chapter 4:  Processes

Chapter four 4.2 Operating System Concepts

Process Concept

An operating system executes a variety of programs: Batch system – jobs (作业) Time-shared systems – user programs or tasks (任务)

Textbook uses the terms job and process almost interchangeably.

Process – a program in execution; a program is a passive entity,while a process is an active entity (进程是有生命的,程序是无生命的)

A process must include: Text section(program code ,程序代码 ) Current activity(program counter&processor register ,当前状态

) Stack (存放临时数据:如函数参数、返回地址) data section (数据区,存放进程执行时用到的数据)

Page 3: Chapter 4:  Processes

Chapter four 4.3 Operating System Concepts

Process State 进程是活动着的程序,任何进程在任何时刻都处于某一状态 (state):

New( 新建 ): 进程刚被创建,还没提交给系统 Running( 正在运行 ): 占有 CPU. Waiting( 等待 ): 进程因为等待某事件的发生如 I/O 完成,不能继续执行 . Ready( 就绪 ): 万事具备,只欠东风(被执行) . Terminated( 终止 ): 进程已经执行完 .

实际系统中进程的状态划分略有差异 ,如 LINUX: TASK_RUNNING( 就绪或执行 ): R TASK_INTERRUPTIBLE( 可中断等待) . S TASK_UNINTERRUPTIBLE( 不可中断等待 ): D TASK_STOPPED( 暂停 ). T TASK_ZOMBIE( 僵死 ) Z#ps –el 详细列出当前系统中所有的进程,其中的 S 属性即为进程状态# ps ax 按 BSD 格式列出进程,其中的 STAT 属性还列出以下属性: W: has no resident pages <: high-priority process N: low_priority task L: has pages locked into memory(for real-time)

Page 4: Chapter 4:  Processes

Chapter four 4.4 Operating System Concepts

diagram of process state(5 states)

Page 5: Chapter 4:  Processes

Chapter four 4.5 Operating System Concepts

do_fork()

收到 SIG_KILL或 SIG_CONT后,执行 wake_up( )

所申请资源有效, 所申请资源有效时, 或收到 signal后 wake_up()或 wake_up_interruptible()

申请资源未果, schedule( ) 时间片到 申请资源未果, sleep_on() interruptible_s leep_on() schedule() schedule( )

跟踪系统调用,执行 syscall_trace( ) sys_exit( ) schedule( ) do_exit( )

TASK_RUNNI NG

TASK_UNI NTERRUPTI BLE TASK_I NTERRUPTI BLE

拥有 CPU

TASK_STOPPED TASK_ZOMBI E

Linux 进程状态图

Page 6: Chapter 4:  Processes

Chapter four 4.6 Operating System Concepts

Process Control Block (PCB ,进程控制块)

OS 为了管理、控制进程,设置 PCB ,存储进程相关信息

Process state (状态) Program counter (程序计数器) CPU registers (寄存器值) CPU scheduling information (调度信息) Memory-management information (存储管理信息) Accounting information (记帐信息,如 CPU time) I/O status information( I/O 状态信息,如打开的文

件)

Page 7: Chapter 4:  Processes

Chapter four 4.7 Operating System Concepts

Process Control Block (PCB)

Page 8: Chapter 4:  Processes

Chapter four 4.8 Operating System Concepts

CPU Switch From Process to Process

Page 9: Chapter 4:  Processes

Chapter four 4.9 Operating System Concepts

进程调度队列 (Process Scheduling Queues)

作业队列 (Job queue) – set of all processes in the system. 就绪队列 (Ready queue) – set of all processes residing in

main memory, ready and waiting to execute. 设备队列 (Device queues) – set of processes waiting for

an I/O device. OS 调度进程,使进程在各队列间迁移 ( migrate)

Page 10: Chapter 4:  Processes

Chapter four 4.10 Operating System Concepts

Ready Queue And Various I/O Device Queues

Page 11: Chapter 4:  Processes

Chapter four 4.11 Operating System Concepts

进程在各队列间迁移(方块表示队列,圆圈表示资源)

Page 12: Chapter 4:  Processes

Chapter four 4.12 Operating System Concepts

调度( schedulers ,选择进程在各队列间迁移)

Long-term scheduler (or job scheduler ,作业调度) – selects which processes should be brought into the ready queue.

- always appears on batch systems, not present on time-sharing OSs like UNIX. (往往在批处理系统中出现,以控制系统中的并行作业数 )

Short-term scheduler (or CPU scheduler, CPU调度 ) – selects which process should be executed next and allocates CPU.

Medium-term scheduler(swapping ,对换 ) – swap in, swap out, partially executed processes

Page 13: Chapter 4:  Processes

Chapter four 4.13 Operating System Concepts

对换调度 (Medium Term Scheduling)

Page 14: Chapter 4:  Processes

Chapter four 4.14 Operating System Concepts

Schedulers (Cont.)

Short-term scheduler is invoked very frequently (milliseconds) (must be fast). (频繁发生,毫秒级)

Long-term scheduler is invoked very infrequently (seconds, minutes) (may be slow).

The long-term scheduler controls the degree of multiprogramming.

Processes can be described as either: I/O-bound process( I/O 约束的进程) – spends more time

doing I/O than computations, many short CPU bursts. CPU-bound process(CPU 约束的进程 ) – spends more time

doing computations; few very long CPU bursts.

Page 15: Chapter 4:  Processes

Chapter four 4.15 Operating System Concepts

进程上下文切换 (Context Switch)

When CPU switches to another process, the system must save the state of the old process and load the saved state for the new process. (进程切换时必须保存当前进程的状态,恢复调入进程的状态)

Context-switch time is overhead; the system does no useful work while switching. (很费时,如果系统频繁进行进程切换,将严重影响系统性能)

Time dependent on hardware support.

Page 16: Chapter 4:  Processes

Chapter four 4.16 Operating System Concepts

Operation on process:Process Creation

Parent process create children processes, which, in turn create other processes, forming a tree of processes.

Resource sharing (父子进程共享资源方式) Parent and children share all resources. Children share subset of parent’s resources. Parent and child share no resources.

Execution Parent and children execute concurrently. Parent waits until children terminate.

Page 17: Chapter 4:  Processes

Chapter four 4.17 Operating System Concepts

Process Creation (Cont.)

Address space Child duplicate of parent. Child has a program loaded into it.

UNIX examples fork system call creates new process exec system call used after a fork to replace the

process’ memory space with a new program.

Page 18: Chapter 4:  Processes

Chapter four 4.18 Operating System Concepts

Processes Tree on a UNIX System

Pagedaemon:2# 进程 , swapper:3# 进程 ,init :1# 进程

Page 19: Chapter 4:  Processes

Chapter four 4.19 Operating System Concepts

#include <stdio.h>

void main(){ int pid; pid = fork(); //system call if (pid < 0 ) { //error ocurrred printf(“fork failed.”); exit(-1); //system call } else if (pid == 0 ) { //child process printf(“child process executing…\n”); execlp(“/bin/ls”,”ls”,NULL); //system call } else { //parent process printf(“parent wating…\n”); wait(NULL); //system call, wait for children completion printf(“child complete.”); exit(0); }}

结果:parent waiting…child process executing…<ls result>child complete

Page 20: Chapter 4:  Processes

Chapter four 4.20 Operating System Concepts

Operation on process: Process Termination

Process executes last statement and asks the operating system to delete it (exit).( 主动终止 ) Output data from child to parent (via wait). Process’ resources are deallocated by operating

system. Parent may terminate execution of children processes

(abort).( 被动终止 ) Child has exceeded allocated resources. Task assigned to child is no longer required. Parent is exiting.

Operating system does not allow child to continue if its parent terminates.

Cascading termination.( 级联终止 )

Page 21: Chapter 4:  Processes

Chapter four 4.21 Operating System Concepts

Cooperating Processes

Independent process cannot affect or be affected by the execution of another process.

Cooperating process can affect or be affected by the execution of another process

Advantages of process cooperation Information sharing Computation speed-up Modularity Convenience

Page 22: Chapter 4:  Processes

Chapter four 4.22 Operating System Concepts

Example of cooperating processes:Producer-Consumer Problem

Paradigm for cooperating processes, producer process produces information that is consumed by a consumer process. unbounded-buffer places no practical limit on the

size of the buffer.( 无限缓冲 ) bounded-buffer assumes that there is a fixed

buffer size.( 有限缓冲 )

Page 23: Chapter 4:  Processes

Chapter four 4.23 Operating System Concepts

Bounded-Buffer – Shared-Memory Solution

Shared data#define BUFFER_SIZE 10

Typedef struct {

. . .

} item;

item buffer[BUFFER_SIZE];

int in = 0;

int out = 0;

Page 24: Chapter 4:  Processes

Chapter four 4.24 Operating System Concepts

Bounded-Buffer

Producer:item nextProduced;while (1) {

while (((in + 1) % BUFFER_SIZE) == out) ; /* do nothing */buffer[in] = nextProduced;in = (in + 1) % BUFFER_SIZE;

}

Consumer:item nextConsumed;

while (1) {while (in == out)

; /* do nothing */nextConsumed = buffer[out];out = (out + 1) % BUFFER_SIZE;

}

Solution is correct, but can only

use BUFFER_SIZE-1 elements(why?)

Page 25: Chapter 4:  Processes

Chapter four 4.25 Operating System Concepts

Interprocess communication(IPC)

Mechanism for processes to communicate and to synchronize their actions.

signal (信号机制) : 给其他进程发送异步事件信号。如: # kill –9 pid : 向 pid 进程发送 9 号信号(无条件终止) # kill –l :显示系统中所有的信号

# ls –l | wc –l : 求出当前目录下的文件数 pipe (管道技术) : 一个进程的输出作为另外一个进程的输入

,实现相关进程(如父子进程)通信,可看作一个临时文件。如: 无名管道( pipe):#ls –l | grep ‘^d’ ,实现相同父进程的子

进程间通信。 命名管道 (named pipe, FIFO) :是有名字的管道,在 OS 中作

为一个对象(文件,即 FIFO 文件)存在,实现任何进程间通信 # mkfifo pipename # ls –l > pipename & wc –l < pipename

Page 26: Chapter 4:  Processes

Chapter four 4.26 Operating System Concepts

共享内存 (shared memory,SM) :通过将两个或多个进程地址空间的一部分映射到相同的物理内存来实现共享内存机制,利用共享内存可以实现灵活的进程间通讯机制。但是,内存被共享之后,对共享内存的访问同步需要由其他 IPC 机制,例如信号量来实现。 消息传递 (Message passing)

信号量 (semaphore,第七章讲 )

基于 C/S的 IPC(sockets,RPC,RMI)

消息队列、信号量、共享内存是 UNIX SYSV 中三个经典的 IPC 机制信号及管道是 UNIX 中较早使用的 IPC 机制

Page 27: Chapter 4:  Processes

Chapter four 4.27 Operating System Concepts

IPC:message passing

Message system – processes communicate with each other without resorting to shared variables.

IPC facility provides two operations: send(message) – message size fixed or variable receive(message)

If P and Q wish to communicate, they need to: establish a communication link between them exchange messages via send/receive

Page 28: Chapter 4:  Processes

Chapter four 4.28 Operating System Concepts

Message-passing:Implementation Questions

Direct or indirect communication Synchronization scheme Buffering methods

Page 29: Chapter 4:  Processes

Chapter four 4.29 Operating System Concepts

Message-passing: Direct Communication

Processes exchange messages directly Symmetric: processesmust name each other explicitly:

send (P, message) – send a message to process P receive(Q, message) – receive a message from

process Q Asymmetric: only the sender names the recipient

send (P, message) – send a message to process P receive(id, message) – receive all messages

associated with process “id” Properties of communication link

Links are established automatically. A link is associated with exactly one pair of communicating

processes. Between each pair there exists exactly one link. The link may be unidirectional, but is usually bi-directional.

Page 30: Chapter 4:  Processes

Chapter four 4.30 Operating System Concepts

Message-passing: Indirect Communication

Messages are directed and received from mailboxes (also referred to as ports). Each mailbox has a unique id. Processes can communicate only if they share a

mailbox. Properties of communication link

Link established only if processes share a common mailbox

A link may be associated with many processes. Each pair of processes may share several

communication links. Link may be unidirectional or bi-directional.

Page 31: Chapter 4:  Processes

Chapter four 4.31 Operating System Concepts

Operations create a new mailbox send and receive messages through mailbox destroy a mailbox

Primitives are defined as:

send(A, message) – send a message to mailbox A

receive(A, message) – receive a message from mailbox A

Message-passing: Indirect Communication

Page 32: Chapter 4:  Processes

Chapter four 4.32 Operating System Concepts

Mailbox sharing P1, P2, and P3 share mailbox A.

P1, sends; P2 and P3 receive.

Who gets the message? Solutions

Allow a link to be associated with at most two processes.

Allow only one process at a time to execute a receive operation.

Allow the system to select arbitrarily the receiver. Sender is notified who the receiver was.

Message-passing: Indirect Communication

Page 33: Chapter 4:  Processes

Chapter four 4.33 Operating System Concepts

Message-passing: Synchronization

Message passing may be either blocking or non-blocking.

Blocking is considered synchronous Non-blocking is considered asynchronous send and receive primitives may be either

blocking or non-blocking. The most common case is non-blocking send

and blocking receive

Page 34: Chapter 4:  Processes

Chapter four 4.34 Operating System Concepts

Message-passing: Buffering

Queue of messages attached to the link; implemented in one of three ways.1. Zero capacity – 0 messages

Sender must wait for receiver

2. Bounded capacity – finite length of n messagesSender must wait if link full.

3. Unbounded capacity – infinite length Sender never waits.

Case 1 is also called no buffering

Case 2 and 3 are also called automatic buffering

Page 35: Chapter 4:  Processes

Chapter four 4.35 Operating System Concepts

msgque msgid_ds msg msg

msg_perms

msg_first

msg_last

msg_next msg_next

msg_type

msg_spot

msg_stime

msg_ts

message

Linux 中的消息队列(参见 ipc 目录)

Msgque: 消息队列数组,其下标 subscription 就是相应消息队列的 id;Msgid_ds: 消息队列头,是对某个消息队列的描述,包括访问权限 (msg_perms), 及对队列中消息的管理Msg: 即消息节点

Message queue is also called mailboxIs an indirect message communication method

Page 36: Chapter 4:  Processes

Chapter four 4.36 Operating System Concepts

stati c struct msqi d_ds *msgque[MSGMNI ]; / * i pc/msg. c */struct msqi d_ds { / * 每个消息队列占一个msqi d_ds结构,i ncl ude/ l i nux/msg. h */ struct i pc_perm msg_perm; struct msg *msg_fi rst; / * 指向消息队列的第一条消息 */ struct msg *msg_l ast; / * 指向消息队列的最后一条消息 */ t i me_t msg_st i me; / * 最后发送时间 */ t i me_t msg_rt i me; / * 最后接收时间 */ t i me_t msg_ct i me; / * 最后修改时间 */ struct wai t_queue *wwai t; / * 写消息进程的等待队列 */ struct wai t_queue *rwai t; / * 读消息进程的等待队列 */ ushort msg_cbytes; / * 队列中消息的字节数 */ ushort msg_qnum; / * 队列中的消息数 */ ushort msg_qbytes; / * 队列中消息的最大字节数 */ ushort msg_l spi d; / * 最后一个发送消息的进程的标识号 */ ushort msg_l rpi d; / * 最后一个接收消息的进程的标识号 */};

struct msg { / * 每条消息占一个msg结构,i ncl ude/ l i nux/msg. h */ struct msg *msg_next; / * 后继节点,后一条消息 */ l ong msg_type; / * 消息类型 */ char *msg_spot; / * 消息文本的地址 */ t i me_t msg_st i me; / * 发送此条消息的时间 */ short msg_ts; / * 消息文本的长度 */};

消息队列数据结构:

Page 37: Chapter 4:  Processes

Chapter four 4.37 Operating System Concepts

struct i pc_perm { key_t key; / * 整型,0表示 pri vate,非 0表示 publ i c */ ushort ui d; / * 资源拥有者的有效标识 */ ushort gi d; / * 资源拥有者所在组的有效标识 */ ushort cui d; / * 资源创建者的有效标识 */ ushort cgi d; / * 资源创建者所在组的有效标识 */ ushort mode; / * 访问模式,其意义同文件访问模式 */ ushort seq; / * 序列号 */ };

如果 key是 public,那么任何进程都可通过 key找到该消息队列。

Operations on message queue:

MsggetMsgsendMsgrcvMsgctl

Page 38: Chapter 4:  Processes

Chapter four 4.38 Operating System Concepts

Client-Server Communication

Communications may take place between processes on different machines. Some methods used: Sockets Remote Procedure Calls Remote Method Invocation (Java)

Page 39: Chapter 4:  Processes

Chapter four 4.39 Operating System Concepts

Sockets( 套接字 ) Originated from BSD UNIX A socket is defined as an endpoint for communication. A socket is a concatenation of IP address and port(端口 ) Port: 一个 16位的整数, 1024 以下为系统用,如 23为 telnet service专

用, 21为 ftp server专用, 80为 http server专用,应用程序应使用 1024 以上的端口

The socket 161.25.19.8:1625 refers to port 1625 on host 161.25.19.8 Communication takes place between a pair of sockets. Type of socket: * connection-oriented(TCP,面向连接 ): 可靠 * connectionless(UDP, 无连接) : 可靠性较差,但方便 * multicast( 多播 ): 可以连接至多个节点) Any socket may be either blocking or non-blocking

Page 40: Chapter 4:  Processes

Chapter four 4.40 Operating System Concepts

Socket Communication

Page 41: Chapter 4:  Processes

Chapter four 4.41 Operating System Concepts

A typical C/S communication using sockets

Server side: getprotobyname

socket

bind

listen

accept

send

close

Client side:gethostbyname

getprotobyname

socket

connect

recv

close

Page 42: Chapter 4:  Processes

Chapter four 4.42 Operating System Concepts

Service side:

int sd,sd2;int port = 1280;sd=socket(AF_INET, SOCK_STREAM,0);BindSocket( sd , nPort ) ;ListenSocket( sd );while(1){ sd2=AcceptSocket( sd ); SendData(sd2,databuf); closesocket(sd2);}

client side:

int sd;int port = 1280;sd=socket(AF_INET, SOCK_STREAM,0);ConnectSocket(sd,port);RecvData(sd,databuf);closesocket(sd);

Page 43: Chapter 4:  Processes

Chapter four 4.43 Operating System Concepts

Remote Procedure Calls( 远程过程调用 )

Remote procedure call (RPC) abstracts procedure calls between processes on networked systems.

操作系统中的很多服务 (services)依赖于 RPC 来实现 ,如windows2000 中的COM+、DHCP、DNS server、 remote storage、 telnet 等)

Stubs( 存根 ) –proxy for the actual procedure on the server.(隐藏RPC 调用的细节 )

The client-side stub locates the server and packs and sends the parameters The server-side stub receives this message, unpacks the parameters, and

performs the procedure on the server. 一个 RPC服务对应一个 port (端口,就像 socket 中的 port),如果 client 不知道某个 RPC的 port ,可以询问 matchmaker (媒人 ),matchmaker也是一个服务,但它占用固定的 RPC端口

OSF-DCE:open software foundation-distributed computing environment ,一个 RPC标准,要求 RPC简洁、透明、高效

Page 44: Chapter 4:  Processes

Chapter four 4.44 Operating System Concepts

Remote Procedure Calls

Microsoft RPC :基于 OSF RPC - MIDL:Microsoft Interface Definition Language,接口描述语言,用它来描述对远程过程的访问

- MIDL编译器生成相应的 stub - stub 调用 client side run-time library 来发送请求及参数

- server端完成相应的过程

Page 45: Chapter 4:  Processes

Chapter four 4.45 Operating System Concepts

Page 46: Chapter 4:  Processes

Chapter four 4.46 Operating System Concepts

Remote Method Invocation( 远程方法调用 )

Remote Method Invocation (RMI) is a Java mechanism similar to RPCs.( JAVA版的 RPC)

RMI allows a Java program on one machine to invoke a method on a remote object.(允许应用程序调用一个异地对象的方法 )

Page 47: Chapter 4:  Processes

Chapter four 4.47 Operating System Concepts

RMI 的参数传递


Recommended