Sei sulla pagina 1di 30

What is a process?

How does the dispatcher


Questions context switch between
Processes answered in this
processes?

Dr. P Sai Kiran lecture: How does the OS create a


new process?

Adapted From :Andrea C. Arpaci-Dusseau


Remzi H. Arpaci-Dusseau
• A process is different than a program
• Program: Static code and static data
• Process: Dynamic instance of code and data
Processe
s vs.
• No one-to-one mapping between programs and processes
Program
• Can have multiple processes of the same program
s Example: many users can run “ls” at the same time
• One program can invoke multiple processes
Example: “make” runs many processes to accomplish its work
Process Creation

A process includes three segments/sections:


1. Program: code/text.
2. Data: global variables and heap
Heap contains memory dynamically allocated during
run time.
3. Stack: temporary data
Procedure/Function parameters, return addresses,
local variables.
Stack: Automatically allocates and deallocates
memory for the function variables
Heap: It is the responsibility of the user to
deallocate memory or memory leak will happen
General Structure of OS Control
Tables
System Classifications

All systems support processes, but the number varies

Uniprogramming Multiprogramming
Only one process resident at a time Multiple processes resident at a time (or,
multitasking)
Examples:
First systems and DOS for PCs Multiprocessing: Systems with multiple
processors
Advantages:
Runs on all hardware Examples: Unix variants, WindowsNT

Disadvantages: Advantages: Better user convenience and


Not convenient for user and poor system performance
performance
Disadvantages: Complexity in OS
Multiprogramming
OS requirements for multiprogramming

Mechanism Policy

To switch between processes To decide which process to schedule


To protect processes from one another
How it is done:
How it is done: Decision-maker to optimize some
Low-level code that implements the workload performance metric
decision
Dispatch
OS runs dispatch loop Mechanism
while (1) {
run process A for some time­slice
stop process A and save its context Context-switch
load context of another process B
}

Question 1: Question 2:
How does dispatcher gain control? What execution context must be saved
and restored?
Direct execution

Direct execution
• Allow user process to run directly on hardware
• OS creates process and transfers control to starting point (i.e., main())
Problems with direct execution?
1. Process could do something restricted
Could read/write other process data (disk or memory)
2. Process could run forever (slow, buggy, or malicious)
OS needs to be able to switch between processes
3. Process could do something slow (like I/O)
OS wants to use resources efficiently and switch CPU to other process
Q1: Hardware for Multiprogramming
Need:
Must differentiate application process and OS

Hardware support:
Bit in status word designates whether currently running in user or system mode

System mode (or privileged or supervisor)


Allows functionality Execution of special instructions (e.g., access hardware devices)
Access to all of memory
Change stack pointer

Usage
Applications run in user mode
OS runs in system mode
Q1: Entering system mode
How does OS get control?
Synchronous interrupts, or traps Asynchronous interrupts
Event internal to a process that gives control Events external to a process, generated
to OS by hardware
Examples:
System calls, page faults (access page not in Examples:
main memory), or errors (illegal instruction or Characters typed, or completion of a
divide by zero) disk transfer

How are interrupts handled?


Each type of interrupt has corresponding routine (handler or interrupt service routine (ISR)
Hardware saves current process and passes control to ISR
Print() of C language and its Unix System
call
System Call Implementation
• A number is associated with each system call.
• System-call interface maintains a table indexed according to these numbers
• The system call interface invokes the intended system call in OS kernel and returns
status of the system call and any return values
• The caller need not know a thing about how the system call is implemented
• Exact type and amount of information vary according to OS and call

Method 1: Method 2: Method 3


Pass the parameters in Parameters stored in a Parameters placed, or pushed,
registers block, or table, in memory, onto the stack by the program
In some cases, may be and address of block and popped off the stack by
more parameters than passed as a parameter in a the operating system
register
registers
This approach taken by
Linux and Solaris
Types of System Calls • File management
• create file, delete file
• Process control • open, close file
• Communications
• read, write, reposition
• create process, terminate • create, delete
• get and set file attributes
process communication connection
• Device management
• end, abort • send, receive messages if
• request device, release device
• load, execute message passing model to
• read, write, reposition
host name or process name
• get process attributes, set • get device attributes, set
• From client to server
process attributes device attributes
• Shared-memory model
• wait for time • logically attach or detach
create and gain access to
devices
• wait event, signal event memory regions
• Information maintenance
• allocate and free memory • transfer status information
• get time or date, set time or
• attach and detach remote
• Dump memory if error date
devices
• Debugger for determining • get system data, set system
• Protection
bugs, single step execution data
• Control access to resources
• get and set process, file, or
• Locks for managing access • Get and set permissions
device attributes
to shared data between • Allow and deny user access
processes
System Call Implementation
Q1: How does
Dispatcher run?
Option 1: Cooperative Multi-tasking
Trust process to relinquish CPU through traps
Trap: Event internal to process that gives control to OS

Examples:
System call, page fault (access page not in main memory), or error (illegal instruction or divide by
zero)

Disadvantages:
Processes can misbehave
By avoiding all traps and performing no I/O, can take over entire machine
Only solution: Reboot!
Not performed in modern operating systems
Q1: How does
Dispatcher run?

Option 2: True Multi-tasking


Guarantee OS can obtain control periodically.
Enter OS by enabling periodic alarm clock.
Hardware generates timer interrupt (CPU or separate chip).

Example: Every 10ms


User must not be able to mask timer interrupt.
Dispatcher counts interrupts between context switches.

Example: Waiting 20 timer ticks gives 200 ms time slice

Common time slices range from 10 ms to 200 ms


Q2: Process States (Three State
Model)
Each process is in one of three modes:
Running: On the CPU (only one on a uniprocessor)
Ready: Waiting for the CPU
Blocked (or asleep): Waiting for I/O or synchronization to complete
Q2: Tracking Processes

• OS must track every process in system


• Each process identified by unique Process ID (PID)
• OS maintains queues of all processes
• Ready queue: Contains all ready processes
• Event queue: One logical queue per event (e.g.,
disk I/O and locks)
• Contains all processes waiting for that event
to complete
Q2: Process States (Five State Model)
Terminated
Running State:
State:
The
NewProgram
Ready process
state – istermination
State– running. moves
••OSIf the
theperformed
Process
has process
scheduler to this
is admitted wants
the state.
i.e to
the
schedule
It is noactions
necessary
required longer
another
resourceseligible
to task
arethe
create forthe
process
execution.
process:
available moves to ready
and waiting for the
hasstate.
scheduler
created ato process
schedule identifier,
the
•tables
If the
process.process
needed tocalls
managesystemthe
calls
•process.
Processfor completes
I/O it goes its to waiting
I/O
butstate.
Operation
has not yet socommitted
it is ready for to
•execute
If the the
process
execution andcalls
process Exit()
waiting
becauseforthen
the
resourcesprocess
scheduler goes
aretolimited. to
dispatch
terminated state.
Q2: What Context must be Saved?

• Dispatcher must track context of process when not running


• Save context in process control block (PCB) (or, process descriptor)
• What information is stored in PCB?
• PID
• Process state (I.e., running, ready, or blocked)
• Execution state (all registers, PC, stack ptr)
• Scheduling priority
• Accounting information (parent and child processes)
• Credentials (which resources can be accessed, owner)
• Pointers to other allocated resources (e.g., open files)
Requires special hardware support
• Hardware saves process PC and PSR on interrupts
How is it done
Operating System Hardware Program
Process A

timer interrupt
save regs(A) to k-stack(A)
move to kernel mode
jump to trap handler

Handle the trap


Call switch() routine
save regs(A) to proc-struct(A)
restore regs(B) from proc-
struct(B)
restore regs(B) from k-
switch to k-stack(B) stack(B)
return-from-trap (into B) move to user mode
jump to B’s IP
Process B

Multiprogramming and Memory

Does OS need to save all of memory between processes?


Option 1: Option 2: Option 3:
Save all of memory to disk Trust next process to not Protect memory (and files)
overwrite memory from next process
Example: Requires hardware support
Alto, early personal Example: Investigate later in course
workstation Early multiprogramming in
PCs and Macs (single user)
Disadvantage:
Very time consuming Disadvantage:
How long to save a 10 MB Very hard to track down bugs
process to disk?
Process Creation
Two ways to create a process
Build a new empty process from scratch
Copy an existing process and change it appropriately

Option 1: New process from scratch


Steps
1. Load specified code and data into memory;
Create empty call stack
2. Create and initialize PCB (make look like context-switch)
3. Put process on ready list
Advantages: No wasted work
Disadvantages:
Difficult to setup process correctly and to express all possible options
Process permissions, where to write I/O, environment variables
Example: WindowsNT has call with 10 arguments
Process Creation
Option 2: Clone existing process and change
fork() and exec() system calls

The fork() System Call


• fork() is used to create processes. It takes no arguments and returns a process ID

• The purpose of fork() is to create a new process, which becomes the child process of the
caller.
• After a new child process is created, both processes will execute the next instruction
following the fork() system call.

• If fork() returns a negative value, the creation of a child process was unsuccessful.
• fork() returns a zero to the newly created child process.
• fork() returns a positive value, the process ID of the child process, to the parent.
Process Creation

The fork() System Call

246 246
67 68

pid pid
=24668 =0
Process Creation wait()
prompt> ./p1 hello world (pid:29146)
hello, I am child
parent(pid:29147)
of 29147 (pid:29146)
hello, I am parent of 29147 (pid:29146)
child (pid:29147) prompt>
prompt>
Process Creation
prompt> ./p2 hello world (pid:29266)
hello, I am child (pid:29267)
hello, I am parent of 29267 (wc:29267)
(pid:29266) prompt>

The system call wait() is easy. This function blocks the calling process until
one of its child processes exits or a signal is received.
Process Creation
Execute a Program: the execvp() System Call

The created child process does not have to run the same program as the parent process
does.
The exec type system calls allow a process to run any program files, which include a binary
executable or a shell script.

The execvp() system call requires two arguments:


1.The first argument is a character string that contains the name of a file to be executed.
2.The second argument is a pointer to an array of character strings. More precisely, its type
is char **, which is exactly identical to the argv array used in the main program:
int main(int argc, char **argv)
Note that this argument must be terminated by a zero.
Process Creation
/execDemo.c
//EXEC.c
#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h> prompt> ./execDemo
#include<unistd.h>
int main() I AM EXEC.c called by execvp()
int main()
{
{
int i;
char *args[]={"./EXEC",NULL};
printf("I am EXEC.c called by execvp() ");
execvp(args[0],args);
printf("\n");
printf(“This should not print");
return 0;
}
return 0;
}
Process Creation
Option 2: Clone existing process and change
fork() and exec() system calls

fork vs exec

• fork starts a new process which is a copy of the one that calls it, while exec
replaces the current process image with another (different) one.

• Both parent and child processes are executed simultaneously in case of


fork() while Control never returns to the original program unless there is an
exec() error.

Potrebbero piacerti anche