Sei sulla pagina 1di 83

Slide 6-1

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-2

Implementing 6
Processes, Threads,
and Resources

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-3
Processes

Process Concept
Process Scheduling
Operating on Processes
Threads

Internet Links to Multi-threads:


IBM
Tom Wagner Site

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-4
Process Concept

An operating system executes a variety of programs:


Batch systems -- Jobs
Time-Shared system -- user programs or tasks
A Process -- a program in execution
A Process -- a schedulable unit of computation
There may be several processes executing the same
program at the same time.
E.g. several users running program at the same time:
Each instance of program creates a separate process.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Implementing the Process Abstraction Slide 6-5

Pi CPU Pj CPU Pk CPU

Pi Executable Pj Executable
Pk Executable
Memory Memory Memory

OS interface

Machine Executable Memory


- The OS is loaded into the OS Address
machines executable CPU Space
memory
- When the computer Pi Address
started, OS begin to ALU Space
execute
- OS chooses to execute a Pk Address
process on an abstract Space
machine, it causes the
processor to branch to the
Control
Unit
block that contains the Pj Address
code for the target abstract Space
machine

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-6
External View of the Process Manager

Application
Program

fork() CreateThread()
wait() CloseHandle() CreateProcess()
exec() WaitForSingleObject()
Memory Mgr

Memory Mgr
Process Mgr

Process Mgr
Device Mgr

Device Mgr
File Mgr

File Mgr
UNIX Windows

Hardware

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-7

Process Manager
In a multi-programmed OS, several processes
can be executed at the same time.
The Process Manager is that part of the OS
that is responsible for managing all the
processes on the system.
When the computer is powered on, there is only
one program in execution: the initial process.
The initial process creates the OS, which can
then create other processes as needed.
A process can create another process with a
system call (e.g. fork in UNIX).
The created process is called a child process
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-8
Process Manager
When a process is created, it specifies to the
Process Manager its resource needs (e.g.
memory requirements, files etc.)
The Process Manager allocates the needed
resources and causes the process to be
executed.
The process manager is responsible
for monitoring the state of each process executing on
the system
process scheduling on CPU
process synchronization and deadlock
protection & security

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-9
Process Manager Responsibilities
Define & implement the essential characteristics of a
process and thread
Algorithms to define the behavior
Data structures to preserve the state of the execution
Define what things threads in the process can reference
the address space (most of the things are memory
locations)
Manage the resources used by the processes/threads
Tools to create/destroy/manipulate processes & threads
Tools to time-multiplex the CPU Scheduling the
(Chapter 7)
Tools to allow threads to synchronization the operation
with one another (Chapters 8-9)
Mechanisms to handle deadlock (Chapter 10)
Mechanisms to handle protection (Chapter 14)

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-10

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process Model Slide 6-11

A process is composed of the following


elements:
Address space which the executing program can
reference-byte-addressable resources
a program (code) to define the behavior of the
process
The data operated on by the process
A set of resources to provide an environment for
execution
A Process Descriptor / identifier: a record kept by
the OS to keep track of the progress of each process.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-12
Modern Processes and Threads
Thrdj in Pi Thrdk in Pi

Pi CPU

OS interface


Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-13
Processes &Threads
State

Stack
State

Stack
Map
Address Space

Program
Map

Static data
Resources

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process Address Space Slide 6-14

Process address space is the


collection of addresses that a Stack Section
thread can reference
(memory)
A process address
Data Section
space includes:
Program text
program code
data section
stack section
Main Memory
Process Descriptor is kept
in OS space.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-15
The Address Space
Address Address Executable
Space Binding Memory

Process
Files

Other objects

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-16
Building the Address Space
Some parts are built into the environment
Files
System services
Some parts are imported at runtime
Mailboxes
Network connections
Memory addresses are created at compile
(and run) time

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-17

Tracing the Hardware Process

Machine is Bootstap Process Interrupt


Powered up
Loader Manager Handler P1 P,2 Pn
Hardware process progress

Load the kernel


Initialization
Execute a thread
Schedule
Service an interrupt

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-18
The Abstract Machine Interface
The abstract machine would export the same instruction set
as the underlying hardware
However, some instructions are used by OS to manage
resource sharing.
Eg: if device I/O instructions could be executed in user mode, then
any program could read or write any part of the disk device,
preventing the OS from providing an adequate file sharing and
protection model. The hardware distinguishes whether sharing or
not.
All abstract machine operations that require execution of a
privileged instruction are implemented by an OS function
This means that the abstract machine interface has two
kinds of instruction: User mode hardware instructions and
OS functions.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
The Abstract Machine Interface Slide 6-19

Application Program

Abstract Machine Instructions


Trap
Instruction fork()

User Mode
open() create()
Instructions

OS

User Mode Supervisor Mode


Instructions Instructions
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-20
The Process Abstraction
The process manager creates the environment in which
multiple processes coexist, each with its own abstract
machine.
When the hardware process begins to execute OS code, it
will execute an algorithm that switches the hardware
process from one context to another.
These context switches can occur whenever the OS gets
control of the processor
Process/thread makes system call (trap execution)
Device interrupt occur

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-21
Context Switch
- When hardware process begins to execute OS code, it
will execute an algorithm that switches the hardware
process from one context to another.
- Context switches can occur whenever the OS gets
control of the processor.
- OS gets control whenever a process or thread makes
a system call.
- 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
- A context switch is the action taken by the hardware
process when it suspends execution on one program
and begins execution on another.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-22
Context Switching
Executable Memory
1
Initialization Process 4. The process
manager switches to
Manager
P2.
7 8
Interrupt 5. P2 makes a system
Interrupt
1. The loader call.
Handler
branches to the 6. The process
OS so that it can 2 manager switches to
initialize. 3 Pn
2. The process P1 7. An interrupt occurs.
manager switches 4
to P1.
8. The interrupt
9 5 handler branches to
3. P1 makes a P2
system call, which the context switch
ultimately 6 algorithm
branches to the 9. The process
part of the process Pn manager switches to
manager that P2.
perform context 10. And so on
switches.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-23
Context Switching
Each individual process/thread can only reference
instructions that are stored in the part of executable
memory associated with the address space.
This means that a context switch can only be done with
one or more privilege instructions
The process manager does all the context switching among
processes/threads
When a process is created, the process manager algorithm
creates a data structure (called the process descriptor)to
keep all the details it requires for managing the process.
The process manager then examine what program should
be loaded into the address space

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-24

Then the process manager creates the


address space and binds the program
addresses into the address space
The process manager can add all other
required abstract machine resources to the
process
At this point, the process manager is ready
to create a base thread so that the program
can be executed within the process
framework.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process Descriptors Slide 6-25

Is the data structure where the OS will keep all


information it needs to manage that process.
OS creates/manages process abstraction
Descriptor is data structure for each process
Register values
Logical state
Type & location of resources it holds
List of resources it needs
Security keys
etc. (see Table 6.3 and the source code of your favorite
OS)

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process Descriptor Slide 6-26

Contains information associated with a process:


PID internal name of the process
Process state the base threads current state
Owner a process has an owner
Parent process
List of child processes
list of allocated resources
list of open files
.
Copy of CPU registers at the last time the
process executed on the CPU
Process Descriptor Table
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-27
Process Descriptor
Each process descriptor is allocated when
the process is created and deallocated when
the process is terminated.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Windows NT Process Descriptor Slide 6-28

EPROCESS
KPROCESS

NT Kernel uint32 KernelTime;
uint32 UserTime;

Byte state;

NT Executive
void *UniqueProcessId;

The Windows NT OS is implemented in the NT Kernel and the NT Executive, which are two separate
sets of software. A process descriptor is implemented in part by NT Kernel and in part by NT Executive.
The part of process descriptor managed by the NT Kernel relates to object management, interrupt handling,
and thread scheduling. The NT executive handles all other aspects of a process.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-29
Windows NT Process Descriptor (2)

Kernel process object including:


Pointer to the page directory
Kernel & user time
Process base priority
Process state
List of the Kernel thread descriptors that are
using this process

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-30
Windows NT Process Descriptor (3)
Parent identification
Exit status
Creation and termination times.
Memory status
Security information
executable image
Process priority class used by the thread scheduler.
A list of handles used by this process
A pointer to Win32-specific information

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Windows NT Thread Descriptor Slide 6-31

EPROCESS
KPROCESS

ETHREAD

KTHREAD
NT Kernel

NT Executive

The windows NT thread descriptor is implemented in the same manner as the process
descriptor. In the example, KTHREAD structure is managed by the NT Kernel, and
contains the information required by the OS when it schedules the thread for execution.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-32
Creating a Process in UNIX

pid = fork();

UNIX kernel

Process Table


Process Descriptor

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process Model CONTD Slide 6-33

Process creation/initialization:
Process Descriptor is created and initialized
Resources needed by the process are allocated (e.g.
files, memory to store code, data, and stack).
Process may inherent some resources from its
parent (e.g. open files, etc.)
Process Descriptor must reflect all allocated
resources
Process is loaded in memory, into its Address Space,
ready to begin execution
From then on, process competes for CPU and other
resources with other processes.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-34
Process Creation

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-35
Process Creation

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-36
Process Termination
Process executes last statement and asks the
operating system to delete it
process resources are de-allocated by the operating
system
A process may be terminated by another process
A parent terminates the execution of its children
When a process exits what happens to its children?
do not allow a child to exist if its parent has terminated
==> cascaded termination (VMS)
allow children to exist after parent ==> orphan
processes (UNIX )

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-37
Creating a Process in NT
CreateProcess();

Win32 Subsystem

ntCreateProcess();

ntCreateThread();

NT Executive

Handle Table

NT Kernel

Process Descriptor

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-38
Windows NT Handles

Application
Handle
User Space
Supervisor Space

Executive Object
NT Executive
Kernel
Object

NT Kernel

- A handle is associated with every abstract resource allocated to a process


- This means that a parent process has a collection of handles for all the
resources it created.
- The parent process can give any subset of these handles to the child process
at creation time. For example, to open files but not for any other resources.
- Whenever a memory mapped resource is allocated to the abstract machine
(process), its components are also bound into the address space.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-39
State Diagram
State summary status of the process/thread
The state variable summarizes the process/thread status by
individual values such as the process is blocked or the
process is currently using the processor.
State Diagram represents the different states in which the
thread can be at different times, along with the transitions
from one state to another that are possible in the OS.
The process manager causes the process/thread to change
state by administering the process, for example by
allocating the processor to process/thread, by blocking the
process/thread until a resource is allocated to it, or by
noting that the process is ready to use the processor.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-40
Simple State Diagram
Request
Done
Running

Request Schedule

Allocate Start

Blocked Ready

- The most basic process/thread diagram has three states: running, ready and blocked.
- A process in the running state is using the processor.
- A ready process is waiting for the processor
- A blocked process was running, but requested a resource that was unavailable.
- It will remain blocked until it is allocated the resource.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process States Slide 6-41

The process manager uses the state diagram to determine the


type of services to provide to the process/thread
If the process is in the ready state, it is competing for the
processor.
If the process is in the running state, it can complete the
execution, in which case the process manager will release the
resources it holds and destroy the process.
Alternatively, the process may request a resource when it is in
the running state. If a running process requests and receives a
resource without having to wait, the process is allowed to
continue in the running state.
Otherwise, the process manager removes the process from the
processor, marks its state as blocked, and notifies the resource
manager that the process is waiting for units of its resource.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-42
Process States (cont.)
The OS then calls the scheduler to allocate
the processor to the next selected process in
the ready state.
From the blocked state, the process can
transition to the ready state when the
resource manager allocates the requested
resource. The process is then once again
competing for the CPU.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-43
Process Model CONTD

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-44
Process Scheduling Queues

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
UNIX State Transition Diagram Slide 6-45

Wait by Request
parent Done
Running
zombie
Request Schedule

Sleeping I/O Request


Allocate
Start

Runnable
I/O Complete Resume
Uninterruptible
Sleep Traced or Stopped

- UNIX process can be in any of the 6 states shown in the figure.


- Blocked process can be blocked for I/O (uninterruptible sleep) or waiting for another resource
(sleeping)
- Traced or stopped processes have made a system call and have been suspended so that their
parent can inspect their state at the time of call.
- A zombie state is a child process that terminated, but whose resources are not released until the
parent notices that they are terminated.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-46
Windows NT Thread States

CreateThread
Terminated
Reinitialize Initialized
Dispatch Activate
Exit
Wait Waiting Ready
Running Wait Complete

Wait Complete

Preempt
Select
Transition

Dispatch
Standby

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-47
Process Model CONTD
Each process uses resources as it executes; main
memory, I/O devices, files, and the CPU
The CPU is also a hardware resource
During execution a process may request other
resources (e.g. more memory) and may release some
of its resources ==> dynamic allocation/de-allocation
When a process can NOT get its requested resources it
gets blocked in a queue waiting for that resource.
Multiprogramming: While one process uses the CPU,
the remaining are using I/O resources or waiting for a
resource (I/O or CPU) to be available.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-48
Resources
Resource: Anything that a process can request, then be
blocked because that thing is not available.

R = {Rj | 0 j < m} = resource types


C = {cj 0 | RjR (0 j < m)} = units of Rj available

Reusable resource: After a unit of the resource has been


allocated, it must ultimately be released back to the
system. E.g., CPU, primary memory, disk space, The
maximum value for cj is the number of units of that
resource
Consumable resource: There is no need to release a
resource after it has been acquired. E.g., a message,
input data, Notice that cj is unbounded.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-49
Using the Model
There is a resource manager, Mgr(Rj) for every Rj
Process pi can request units of Rj if it is currently running
pi can only request ni cj units of reusable Rj
pi can request unbounded # of units of consumable Rj
Mgr(Rj) can allocate units of Rj to pi

request

Process Mgr(Rj)

allocate

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
A Generic Resource Manager Slide 6-50

Resource Manager
Policy Blocked Processes
ProcessProcess
Process
request()
Process
release()

Resource Pool

- All resource managers have the general form shown in the figure
- A process requests units of the resources
- If the resource manager allocates the resource, then the process continues to run
- Otherwise, it is placed in a pool of blocked processes to await allocation.
- Upon allocation, the process is removed from the pool and made ready to run.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-51
Process Hierarchy

Hierarchy allows the community of


processes to agree on basic tasks such as
which processes and how resources should
be allocated to processes
A parent can have many child processes and
each child has exactly one parent

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-52
Process Hierarchies
Parent-child relationship may be significant:
parent controls childrens execution
Request
Done
Running
Yield Suspend
Request Schedule
Suspend Start
Ready-Active
Activate Ready-Suspended
Allocate Allocate
Suspend
Blocked-Active Blocked-Suspended
Activate
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-53
Process Manager Overview
Program Process

Abstract Computing Environment

File Deadlock Process


Manager Protection Description

Synchronization
Device Memory Resource
Manager Manager Scheduler Resource
Resource
Manager
Manager
Manager

Devices Memory CPU Other H/W

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-54
UNIX Organization
Process
Process
Libraries
Process

System Call Interface


File Deadlock Process
Manager Protection Description

Synchronization
Device Memory Resource
Manager Manager Scheduler Resource
Resource
Manager
Manager
Monolithic Kernel Manager

Devices Memory CPU Other H/W


Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-55
Windows NT Organization

T Process
Process T
T T T T
T T Process
T
Libraries
Subsystem Subsystem Subsystem
User

NT Executive
NT Kernel I/O Subsystem
Hardware Abstraction Layer

Processor(s) Main Memory Devices

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-56
UNIX Processes

Each process has its own address space


subdivided into code, data & stack
a.out file describes the address apace
OS creates a Process Descriptor to
manage each process. The collection of
all Process Descriptors is referred to as
the Process Descriptor Table

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-57

UNIX Processes
Each process is assigned a unique process ID
(PID)
The PID is essentially a pointer into the Process
Table of the OS.
A process can use the system call getpid() to
obtain its own PID
Each process has one parent process (the
process that created it), except for process 1
Process 1 ( the init process) is the ancestor of
all other processes
a process can use the system call getppid()
to obtain the PID of it parent (i.e. PPID)

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-58
UNIX Processes
When Unix is first started, it has only one
process. The process is called "init", and its
PID is 1.
The "init" process creates other operating
system processes to do OS functions
For each port supporting user logins (e.g. a
terminal), init creates a process running the
getty program.
The getty process waits for a user to begin
using the port.
When the port begins to be used, getty creates a
new process to run the login program.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-59

UNIX Processes
The login process prompts the user for
username and password, reads the username
and password and verifies by looking up the
/etc/passwd file.
If login successful, the login process changes
directory to the user's directory and creates a
new process running the shell program
specified in the user's entry of the /etc/passwd
file.
The shell process displays a "shell prompt" on
the terminal and waits for the user to type a
command.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-60
UNIX Processes
When the user types a command, the shell
process, reads it, parses it, verifies it, and
creates a new process running the program
specified in the command. In the mean time,
the shell process gets suspended until the
command process finishes.
When the command process is done, the shell
process is resumed again.
When the user logs out, the shell process is
terminated and the login process is resumed,
etc. etc. etc.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-61
UNIX Processes

UNIX fork creates a process


UNIX wait allows a process to wait for
a child to terminate
UNIX exec allows a child to run a new
program

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-62
Creating Processes
UNIX fork() creates a process
fork( ) creates a child process that is identical
to its parent, except that it has:
a different and unique PID
a different PPID
fork()
creates a new address space for the child process
copies code, data and stack into new address space
provides child with access to open files of parent.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-63
Process Creation: fork
int pid;
pid = fork();
the fork is called by the parent but returns in
both the parent and the child
In the parent, it returns the PID of the child process
in the child it returns 0
If fork() fails no child is created and -1 is
returned to the parent.
After the child is created, the parent and the
child processes execute concurrently starting
from the instruction following the fork.
Since only one can be using CPU at a time,
either may go first.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Process Creation: fork Slide 6-64

int pid;
pid = fork( );
if ( pid == 0 )
{
/* code for child here */
exit(0);
}
if (pid < 0)
{
/* fork failed... Put error handling
code here */
}
/*remaining code for parent goes here */

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-65
#include <stdio.h>
int main( )
{ int pid;
if ( (pid = fork( ) ) == 0 )
{ printf(I am the child, my pid=%d and my
parent pid=%d\n, getpid( ), getppid( ) );
exit(0);
}
if (pid < 0)
{ fprintf(stderr, fork failed\n)
exit(1);
}
printf(I am the parent, my pid=%d\n, getpid( ) );
}
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-66
Example: Chain of Processes
#include <stdio.h>

int i, n, pid;
for (i=1, i < n; ++i )
if ( ( pid=fork() ) != 0)
break;
fprintf(stdout,This is process %d with
parent %d\n, getpid(),getppid() );

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-67
Example: a fan of processes
#include <stdio.h>
int i, n, pid;
for (i=1, i<n; ++i)
if ( (pid=fork()) == 0)
break;
fprintf(stdout,This is process %d with
parent %d\n, getpid(),getppid() );

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-68

Synchronization of Parent and


Child
What happens to the parent after it creates a child?
They both execute concurrently
If parent wants to wait until the child terminates
before proceeding further it executes a wait()
or waitpid() system call.
When a process is terminated (with exit( ) ), a
signal is sent to its parent notifying it of the
termination.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-69
exit( )
void exit(int status)
exit( ) closes all process' file descriptors, de-
allocates code, data, and stack, and then terminates
the process.
It sends a signal to the parent process telling of its
termination status and waits until the parent
accepts the signal.
A process that is waiting for its parent to accept its
termination is called a "zombie"
A parent accepts a child's termination by
executing wait( ).

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-70

Synch. of Parent and Child


int pid;
pid = fork( );
if ( pid == 0 )
{
/* child executes this part
concurrently with parent */
exit(0);
}
/*parent works concurrently with
child and independent of each
other*/

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-71
Synch. of Parent and Child
int pid;
pid = fork( );
if ( pid == 0 )
{
/* child executes this part
concurrently with parent */
exit(0);
}
wait(...); /* parent waits for
child*/
/*parent proceeds*/
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-72
Synch. of Parent and Child

If a parent terminates without waiting for a


child, child becomes an orphan and is
adopted by the system init process by
setting their PPID to 1.

init periodically executes wait( ) to remove


zombies from the system.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-73
Wait()
#include <sys/wait.h>
int wait(int *status);

1. if there are no child processes, wait returns


with
-1 (an error)
2. if one or more processes are already in the
zombie state, wait selects an arbitrary one,
stores its status in status , and returns its
PID
3. otherwise, wait sleeps until one of the child
processes terminates and then goes to step 2
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-74
Child Executing a Different
Program
Parent process calls fork to create a child process
child process calls an exec system call.
The exec system call replaces the address space of
the child with a new program
several exec calls:
execv, execvp, etc.
int execv(char *filename, char *argv[ ]);
filename is the name of an executable file
argv is the command-line arguments for the
executable program.
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
main( ) {
Example:Parent Slide 6-75

int pid;
/*code to set up the argv array for the child here*/
pid = fork();
if (pid==0)
{
execv(child_prog, argv);
/* execv does not return unless there is an error*/
fprintf(stderr,error in the execterminating child..);
exit(1);
}
wait( ); /*parent waits for child to terminate*/
.}
Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-76
Example:Child

File child_prog.c:

main( )
{
/* code to be executed by child process */

}
child_prog.c must be compiled into an executable
file.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-77

Threads (read Chap2)


A thread (or lightweight process) is a basic unit
of computation. It uses less state and less
resources than heavyweight process

In a system that supports threads, each


(heavyweight) process consist of one or more
threads.
A traditional process is a process with one
thread.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-78
Threads

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-79
Threads

Each thread has its own


thread ID
program counter
stack space
possibly some of its own data
A thread shares with its sibling threads:
code section
data section
operating system resources (e.g. open files, CPU)

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
POSIX Threads Slide 6-80

DEC Unix conforms to the POSIX standard


==> # include <pthread.h>
When a thread is created it is assigned a thread ID,
a stack, a starting address for execution.
pthread_create(ChildID, Thread_attributes,
function_name, arguments)
ChildID is the returned child ID
Thread_attributes: set to NULL for default attributes
function_name: function to be executed by the thread
arguments: a pointer to the argument to be passed to the
function

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-81
Why threads?
Reduced context switching overhead
An application that needs to block occasionally
waiting for I/O (e.g. disk): While one thread waits, a
second thread can run and do other computation==>
better performance for the application.

Windowing systems:
heavyweight process: physical screen manager
a thread for each window: all threads share the same
physical screen.

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-82
Threads for a windows system

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6
Slide 6-83

Why threads?
Since sibling threads use same data segment, data
sharing among cooperating threads is easily achieved
+ Applications that require sharing a common buffer (e.g.
producer-consumer) can benefit from thread utilization.
no protection between threads: synchronization among
threads when accessing shared data must be enforced by the
programmer.
Threads can be used in multiprocessor systems (each
thread runs on a separate processor, they all share
same address space on a shared memory).

Copyright 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6

Potrebbero piacerti anche