university of pennsylvania 9/12/00cse 3801 multiprogramming cse 380 lecture note 3

21
9/12/00 CSE 380 1 University of Pennsylvan Multiprogramming CSE 380 Lecture Note 3

Post on 22-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

9/12/00 CSE 380 1

University of Pennsylvania

Multiprogramming

CSE 380Lecture Note 3

9/12/00 CSE 380 2

University of Pennsylvania

Concurrent Processes: fork(), wait()

• To see how processes can be used in application and how they are implemented, we study at how processes are created and manipulated in UNIX.

• Important source of info on UNIX is “man.”• UNIX supports multiprogramming, so there will be

many processes in existence at any given time. – Processes are created in UNIX with the fork()

system call.– When a process P creates a process Q, Q is

called the child of P and P is called the parent of Q. So, processes are organized as a "family tree."

9/12/00 CSE 380 3

University of Pennsylvania

UNIX Process Control

• At the root of the family tree of a UNIX system is the special process init:– created as part of the bootstrapping procedure– process-id = 1– among other things, init spawns a child to listen to each terminal,

so that a user may log on.– do "man init” learn more about it

• UNIX provides a number of system calls for process control including:– fork - used to create a new process– exec - to change the program a process is executing– exit - used by a process to terminate itself normally– abort - used by a process to terminate itself abnormally– kill - used by one process to kill or signal another– wait - to wait for termination of a child process– sleep - suspend execution for a specified time interval– getpid - get process id– getppid - get parent process id

9/12/00 CSE 380 4

University of Pennsylvania

The Fork System Call

• The fork() system call creates a "clone" of the calling process. Identical in every respect except (1) the parent process is returned a non-zero value (namely, the process id of the child) and (2) the child process is returned zero. The process id returned to the parent can be used by parent in a wait or kill system call.

• Typical usage of fork():pid_t pid;pid = fork();if (pid == 0) {

/* code to be executed by child process */} else {

/* code executed by parent process */}

------------ fork() -----------------> ----------------->

9/12/00 CSE 380 5

University of Pennsylvania

More on fork()

child process is an exact copy of parent except for value returned by the fork() call

other items copied not depicted (e.g. contents of CPU registers) in practice, text segment is shared child process begins its execution by returning from the fork()

call!

Parent Child

text

stack

data

text

stack

data

Openfile

table

Openfile

tableetc.

9/12/00 CSE 380 6

University of Pennsylvania

Example of spawn using fork

1. #include <unistd.h>

2. Main(){

3. pid_t pid;

4. printf(“Just one process so far\n”);

5. pid = fork();

6. if (pid = 0)

7. printf(“I’m the child\n”);

8. else if (pid > 0)

9. printf(“The parent, ch pid =%d\n”,

10. pid);

11. else

12. printf(“Fork returned error code\n”);

13. }

9/12/00 CSE 380 7

University of Pennsylvania

Why fork()?

Often used in conjunction with exec or execve (the real system call)

#include <sys/types.h>

pid_t pid;

if ( ( pid = fork() ) == 0 ) {

execl( "/usr/games/tetris","tetris", "-easy",0 )

} else {

wait( &status )

}

9/12/00 CSE 380 8

University of Pennsylvania

exec System Call

A family of routines, execl, execv, ..., all eventually make a call to execve.

execlp( program_name, arg1, arg2, ..., 0 )

text and data segments of current process replaced with those of program_name

stack reinitialized with parameters open file table of current process remains intact as in example, program_name is actually path

name of executable file containing program

Note: unlike subroutine call, there is no return after this call. That is, the process calling exec is gone forever!

9/12/00 CSE 380 9

University of Pennsylvania

Parent-Child Synchronization

• exit( status ) - executed by a child process when it wants to terminate. Makes status (an integer) available to parent.

• wait( &status ): return pid_t - suspends execution of process until *some* child process terminates– status indicates reason for termination– return value is process-id of terminated

child

9/12/00 CSE 380 10

University of Pennsylvania

Process Termination

• Besides being able to terminate itself with exit, a process can be killed by another process using kill:– kill( pid, sig ) - sends signal sig to process with

process-id pid. One signal is SIGKILL which means terminate the target process immediately.

• When a process terminates, all the resources it owns are reclaimed by the system:– “process control block” reclaimed– its memory is deallocated– all open files closed and Open File Table reclaimed.

• Note: a process can kill another process only if:– it belongs to the same user– super user

9/12/00 CSE 380 11

University of Pennsylvania

How shell executes a command

This is how the command interpreter (the “shell”) executes your commands.• when you type a command, the shell forks a clone of itself• the child process makes an exec call, which causes it to

stop executing the shell and start executing your command

• the parent process, still running the shell, waits for the child to terminate

fork wait

exec exit

parent

child

shell shell

command

….

9/12/00 CSE 380 12

University of Pennsylvania

Background Processing

You may be aware that shell has capability of managing several concurrent processes.

Example: % longjob & % jobs [1] running longjob %

executes longjob in background mode. Notice the shell returns right away without waiting for longjob to finish.

There are also fg, bf, and CTL-Z.

How does shell do this?while (1) { /* main command loop */

/* print prompt *//* read command */if ( ( pid = fork() ) == 0 ) {

execl( cmd, … );}

else {/* store pid in a table */

}}

9/12/00 CSE 380 13

University of Pennsylvania

Multiprogramming (multiple processes)

• For each process, the O.S. maintains a data structure, called the process control block (PCB). The PCB provides a way of accessing all information relevant to a process:– This data is either contained directly in the PCB, or else

the PCB contains pointers to other system tables. • Processes (PCBs) are manipulated by two main

components of the process subsystem in order to achieve the effects of multiprogramming:– Scheduler: determines the order by which processes

will gain access to the CPU. Efficiency and fair-play are issues here.

– Dispatcher: actually allocates CPU to process next in line as determined by the scheduler.

9/12/00 CSE 380 14

University of Pennsylvania

The Process Control Block (PCB)

• The PCB typically contains the following types of information:

• Process status (or state): new, ready to run, user running, kernel running, waiting, halted– Program counter: where in program the process is

executing– CPU registers: contents of general-purpose register

stack pointer, PSW, index registers– Memory Management info: segment base and limit

registers, page table, location of pages on disk, process size

– User ID, Group ID, Process ID, Parent PID, ...– Event Descriptor: when process is in the “sleep” or

waiting state– Scheduling info: process priority, size of CPU quantum,

length of current CPU burst

9/12/00 CSE 380 15

University of Pennsylvania

PCB (cont.)

– List of pending signals– Accounting info: process execution time, resource

utilization– Real and Effective User IDs: determine various privileges

allowed the process such as file access rights– More timers: record time process has spent executing in

user and Kernel mode– Array indicating how process wishes to react to signals– System call info: arguments, return value, error field for

current system call– Pending I/O operation info: amount of data to transfer, addr

in user memory, file offset, ...– Current directory and root: file system environment of

process– Open file table: records files process has open

9/12/00 CSE 380 16

University of Pennsylvania

PCB in Unix

• In UNIX, the notion of a PCB is split in two:– Process Table entry

The process table contains an entry for every process in system. Table is of fixed size (tunable)

– User AreaExtension of a process table entry. Created along with the creation of an actual process.

• These two structures point to each other!

9/12/00 CSE 380 17

University of Pennsylvania

Process States & Transitions

userrunning

kernelrunning

ready to

runasleep

sys callor

interrupt

return

interruptinterrupt return

block/sleep

wakeupcontext switch

permissible

scheduleprocess

9/12/00 CSE 380 18

University of Pennsylvania

Context Switching

• Let us first review the user/system mode distinction.• When system starts (during system bootstrapping or

boot) it is in system mode.• This is process 0 in V.2, which creates process 1 (init).

This process execs /etc/init and is then executing in user mode.

• Process 1, like any user process, continues executing in user mode until one of the following:– interrupt by an asynchronous device like timer, disk,

or terminal– the process makes a system call by executing an

instruction to cause a software interrupt• Occurrence of such an event causes the CPU to switch

to system mode and begin execution appropriate interrupt handler.

9/12/00 CSE 380 19

University of Pennsylvania

When to context switch

• Typically, hardware automatically saves the user PC and PSW when interrupt occurs, and takes new PC and PSW from interrupt vector.

• Interrupt handler may simply perform its function and then return to the same process that was interrupted (restoring the PC and PSW from the stack).

• Alternatively, may no longer be appropriate to resume execution of process that was running because: process has used up its current CPU quantum process has requested I/O and must wait for results process has asked to be suspended (sleep) for some

amount of time a signal or error requires process be destroyed (killed) a “higher priority” process should be given the CPU

• In such a situation, a context switch is performed to install appropriate info for running a new process.

9/12/00 CSE 380 20

University of Pennsylvania

Mechanics of a Context Switch

1 copy contents of CPU registers (general-purpose, SP, PC, PSW, etc.) into a save area in the PCB of running process

2 change status of running process from “running” to “waiting” (or “ready”)

3 change a system variable running-process to point to the PCB of new process to run

4 copy info from register save area in PCB of new process into CPU registers

• Note: context switching is pure overhead and should be done as

fast as possible often hardware-assisted - special instructions for steps 1 and

4 determining new process to run accomplished by consulting

scheduler queues step 4 will start execution of new process - known as

dispatching.

9/12/00 CSE 380 21

University of PennsylvaniaMULTIPROGRAMMING Through CONTEXT SWITCHING

executing

process A process B

i/o request, timeout, ...waiting

save A’s state

restore B’s statedispatch

save B’s state

restore A’s state