0% found this document useful (0 votes)
15 views

Module 1 Introduction

Uploaded by

yowaimo2005gojo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Module 1 Introduction

Uploaded by

yowaimo2005gojo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

OPERATING SYSTEM

MODULE 1

CHAPTER 1 INTRODUCTION TO OPERATING


SYSTEMS
content
• Introduction to operating systems: What Operating
Systems do, Operating System structure, Operating
System operations, Operating System services,
System Calls, System Programs, Design and
Implementation, Operating System structure–
Simple, Layered, Microkernels and Modules.
• SLE: Types of system calls
What is an Operating System?
• Operating system is a program that manages computer hardware
and act as a intermediary between user of a computer and the
computer hardware.

• Operating system goals:

– Execute user programs and make solving user problems easier.


– Make the computer system convenient to use.
– Use the computer hardware in an efficient manner.
Four Components of a Computer System
Computer System Structure
Hardware – provides basic computing resources such as CPU,
memory, I/O devices.

Operating system - controls and coordinates use of hardware among


various applications and users.

Application programs – define the ways in which the system


resources are used to solve the computing problems of the users.
• Word processors, compilers, web browsers, database systems,
video games.

Users - People, machines, other computers.


What Operating Systems do
User’s View – The user view of the computer varies according
to the interface being used.

• Some users may use PC’s. Here the system is designed so that
only one user can utilize the resource, as a result performance
will be good.

• Users sits at a terminal connected to mainframe. These users


share resources and exchange information.

• Operating system is designed in such a way that to have


maximize resource utilization.
What Operating Systems do
System View

•OS is a resource allocator


–to allocate resources (software and hardware) of the computer
system and manage them efficiently. OS is a manager .

• OS is a control program
–Controls execution of programs to prevent errors and improper use
of the computer.

• Kernel
-- The program that executes forever.
Computer Startup
• When a computer is powered up ,it needs to have initial program to
run. This initial program is called bootstrap program stored in ROM
or EPROM, generally known as firmware.

• Initializes all aspects of system and loads operating system kernel


and starts executing the first process known as “init”.

• The occurrence of an event is usually signaled by an interrupt either


through hardware(using system bus) or software(using system call).

• Interrupts are signals sent to the CPU by I/O devices. They tell the
CPU to stop its current activities and execute appropriate part of the
operating system.
Interrupts
•When the CPU is interrupted, it stops what it is doing and immediately
transfers execution to a fixed location.

•The fixed location usually contains the starting address where the
service routine for the process is located.

•The interrupt service routine executes; on completion, the CPU


resumes the interrupted computation .
Computer System Organization
Computer-system operation
– One or more CPUs, device controllers connect through common bus
providing access to shared memory.
– Concurrent execution of CPUs and devices competing for memory
cycles.
Computer-System Operation
• I/O devices and the CPU can execute concurrently.

• Each device controller is in charge of a particular device type.

• Each device controller has a local buffer.

• CPU moves data from/to main memory to/from local buffers.

• Device controller informs CPU that it has finished its operation


by causing an interrupt.
Storage Structure
• The CPU can load instructions only from memory, so any programs
to run must be stored in main memory (RAM).

• Main memory is usually too small to store all needed programs


and data permanently and volatile .

• Extension to main memory is Secondary memory(ROM) which


holds large quantities of data temporarily.

• The most common secondary-storage device is a magnetic disk


which provides storage for both programs and data.

• Most programs are stored on a disk until they are loaded into
memory. Many programs then use the disk as both the source and
the destination of their processing.
Storage-Device Hierarchy
• The wide variety of storage systems in a computer system can be
organized in a hierarchy according to speed and cost.

• The higher levels are expensive, but they are fast.

• As we move down the hierarchy, the cost per bit generally


decreases, whereas the access time generally increases.
How a Modern Computer Works
• Device controller transfers blocks of data from buffer storage
directly to main memory without CPU intervention.
Computer System Architecture
Single Processor Systems
– One CPU capable of executing instructions comes from user
processes including PDA’s and main frames.

Multiple Processor Systems(Tightly coupled system)


– More than one CPU or one CPU with multiple cores.
– Processors share memory and a clock, communication usually
takes place through the shared memory.

Advantages :
1. Increased throughput : By increasing the number of
processors more work will be done in less time. When multiple
process cooperate on task, a certain amount of overhead is
incurred in keeping all parts working correctly.
Multi Processing Systems (Cont.)
2. Economy of scale : Multi processor system can save more
money than multiple processor, since they share peripherals,
mass storage & power supplies.

3. Increased reliability :If a program is distributed properly on


several processors, then the failure of one processor will not halt
the system but it only slows down.

• Symmetric multiprocessing (SMP)


–Each processor runs an identical copy of the operating system.
–Many processes can run at once without performance
deterioration.
–Most modern operating systems support SMP.
Symmetric Multiprocessing Architecture

• Asymmetric multiprocessing
-- Each processor is assigned a specific task; master processor
schedules and allocates work to slave processors.
-- More common in extremely large systems.
Clustered Systems
• Clustered systems gather together multiple CPUs to accomplish
computational work.

• Clustering provides high availability service i.e. service will


continue even if one or more systems in the cluster fail.

• In asymmetric clustering, one machine is in hot stand by mode


which monitors the active server and the other is running the
applications.

• If that server fails, the hot-standby host becomes the active


server.

• In symmetric clustering, two or more hosts are running


applications and are monitoring each other.
Clustered Systems

Memory Layout for Multiprogrammed System


Operating System Structure
Batch Operating System
--In 1980, there was scarcity of computers, main frame
computers are used.
-- 4 Jobs (J1,J2,J3,J4)
-- Efficiency is less and not interactive.

Multiprogramming (1 CPU)
-- Process requires CPU time and I/O time.
-- J1 goes to I/O device then CPU can take other jobs & process it.
-- CPU will not be idle and busy all the times as a result efficiency
will be improved .
-- Time Sharin
Multitasking

-- 4 jobs (J1,J2,J3,J4) CPU will choose J1 for sometime, J2 for


sometime and so on switching to remaining jobs.
-- CPU will be multiplexing all the jobs without completing
anything.
-- Interactivity can be improved
-- Response Time should be less.
(Process, Job Scheduling, CPU scheduling, swapping, virtual memory,

Multiprocessing (Multiple CPU’s)

-- Lots of CPU on a single computer. As a result many jobs can be


processed simultaneously hence parallelism can improved.
-- Makes the processing faster and provides reliability.
-- E.g. : Dual core , Quad core
Operating System Operations
• To ensure the proper execution of the operating system, we must
be able to distinguish between the execution of operating-system
code and user defined code.

• Two separate modes of operation : User mode and Kernel mode.

• A bit, called mode bit is added to the hardware of the computer to


indicate the current mode: kernel (0) or user (1).

• When the computer system is executing on behalf of a user


application, the system is in user mode.

• When a user application requests a service from the operating


system (via a system call), it must transition from user to kernel
mode to fulfill the request.
Timer
• Ensure that operating system maintains control over the
CPU.

• We cannot allow a user program to get stuck in an infinite


loop and never return control to the operating system. To
accomplish this goal , we use timer.

• A timer can be set by the operating system to interrupt the


computer after a specified period. Every time clock ticks,
counter is decremented. When counter reaches 0, an
interrupt occurs.
Process Management
• A process is a program in execution. It is a unit of work within the
system. Program is a passive entity, process is an active entity.

• Process needs resources like CPU, memory, I/O files to accomplish


its task.

• The operating system is responsible for the following activities in


connection with process management:

--Creating and deleting both user and system processes


--Suspending and resuming processes
-- Providing mechanisms for process synchronization
-- Providing mechanisms for process communication
--Providing mechanisms for deadlock handling
Memory Management
• To execute a program, all (or part) of the instructions must be in
memory.

• All (or part) of the data that is needed by the program must be in
memory. Memory management determines what is in memory .

• Memory management activities


– Keeping track of which parts of memory are currently being
used and by whom.
– Deciding which processes (or parts thereof) and data to move
into and out of memory.
– Allocating and deallocating memory space as needed.
Storage Management
• OS provides uniform, logical view of information storage known as
file.

• File-System management
– Files usually organized into directories
– Access control on most systems to determine who can access
what.
– OS activities include
• Creating and deleting files and directories
• Primitives to manipulate files and directories
• Mapping files onto secondary storage
• Backup files onto stable (non-volatile) storage media
Mass-Storage Management
• Usually disks used to store data that does not fit in main memory
or data that must be kept for a “long” period of time.

• Proper management is of central importance.

• Entire speed of computer operation hinges on disk subsystem


and its algorithms.

• OS activities
– Free-space management
– Storage allocation
– Disk scheduling
Caching
• Caching is an important principle of computer systems.

• Information is normally kept in main memory . As it is used,


it is copied into a cache-on a temporary basis.

• When we need a particular piece of information, cache is checked


first to determine if information is there
-- If it is, information used directly from the cache (fast)
-- If not, data is copied to cache under the assumption that we
will need it again soon and used there.

Migration of integer A from disk to register


• In a multiprocessor environment , each of the CPUs also contains a
local cache .Copy of A must exist simultaneously in several caches.

• Since the various CPUs can all execute concurrently ,we must make
sure that update to the value of A in one cache is immediately
reflected to all other caches.

• This situation is called cache coherency.


Distributed System
• A distributed system is a collection of physically separate,
possibly heterogeneous, computer systems that are networked to
provide the users with access to various resources that the
system maintains.

• A network is a communication path between two or more


systems.

• A LAN connects computers within a room , a floor or a building.


• A WAN usually links buildings, cities or countries.
• A MAN could link buildings within a city.

• A NOS(Network OS) is an operating system that provides features


like file sharing across the network which allows different
processes on different computers to exchange messages.
Real Time Embedded System
• Embedded computers are the most prevalent form of computers in
existence and it will have some specific task.
• These devices are found everywhere, from car engines and
manufacturing robots to DVDs and microwave ovens.

Multimedia Systems
• Multimedia data consist of video and audio files such as MP3, DVD
movies, video conferencing, and short video clips of movie
previews or news stories downloaded over the internet.

Handheld Systems
• It includes Pocket-Pc’s, cellular telephones which use
special-purpose embedded operating systems.
• Because of their size, most handheld devices have small amounts of
memory, slow processors, and small display screens.
Computing Environments
Traditional Computing
• In a "typical office environment" consisted of PCs connected to a
network, with servers providing file and print services.

• Portability was achieved by the use of laptop computers.

• At home, most users had a single computer with a slow modem


connection to the office, the internet, or both.

• Today, network-connection speeds are available at great cost and


relatively inexpensive, giving home users more access to more
data.
Client Server Computing

• Server systems can be of two types : Compute server ,File server

• Compute server system provides an interface to which a client can


send a request to perform an action (Eg: to read data) in response,
the server executes the action and sends back results to the client.
E g : A server running a database that responds to client requests
for data.

• File server system provides a file-system interface where clients


can create, update, read, and delete files.
E g : Webserver that delivers files to clients running Web browsers.
Peer to Peer Computing
• No distinguish between clients and servers . All the nodes are
treated as peers(either client or server).

• Here, services can be provided by several nodes distributed


throughout the network.

• To participate in a peer-to-peer system, a node must first join the


network of peers.

• Once a node has joined the network, it can begin providing services
to and requesting services from other nodes in the network.

• When a node joins a network, it registers its service with a


centralized lookup service on the network. Any node desiring a
specific service first contacts this centralized lookup service to
determine which node provides the service.
CHAPTER 2 SYSTEM STRUCTURES
Operating System Services
• Operating systems provide an environment for execution of
programs and services to the users.
File-system manipulation- The file system is of particular
interest. Programs need to read , write files and directories,
create and delete them, search them, list file Information,
permission management.

Communication – Processes may exchange information, on the


same computer or between computers over a network . It can be
shared memory/message passing.

Error detection – Errors occur in the CPU, memory hardware,


I/O devices, user program.
• For each type of error, OS should take the appropriate action
to ensure correct and consistent operation.
• Debugging facilities can greatly enhance the users and
programmers abilities to efficiently use the system.
Operating System Services
Resource allocation - When multiple users or multiple jobs
running concurrently, resources must be allocated to each of
them.

Accounting - To keep track of which users use how much and


what kinds of computer resources.

Protection and security - The owners of information stored in a


networked computer system may want to control use of that
information, concurrent processes should not interfere with
each other.
• Protection involves ensuring that all access to system
resources is controlled.
• Security of the system from outsiders requires user
authentication, extends to defending external I/O devices
from invalid access attempts.
User Operating System Interface - CLI
•One set of operating-system services provides functions that are
helpful to the user:
– User interface - Almost all operating systems have a user
interface (UI).
• Varies between Command-Line(CLI), Graphics User
Interface (GUI), Batch.
CLI or command interpreter allows direct command entry
– Primarily fetches a command from user and executes it.
User Operating System Interface - GUI
User-friendly desktop metaphor interface
– Usually mouse, keyboard, and monitor.
– Icons represent files, programs, actions, etc.
– Invented at Xerox PARC.

Touchscreen Screen Interfaces


-- Mouse not possible or not desired
-- Actions and selection based on gestures
-- Virtual keyboard for text entry
-- Voice commands.
System Calls
• Programming interface to the services provided by the OS.

• Typically written in a high-level language (C or C++).

• System call sequence to copy the contents of one file to


another file.
System Call Implementation
• Typically, a number 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 return values.

• The caller need know nothing about how the system call is
implemented.
– Just needs to obey API and understand what OS will do as a
result of system call.
– Most details of OS interface hidden from programmer by API.
• Managed by run-time support library (set of functions built
into libraries included with compiler).
API – System Call – OS Relationship
Standard C Library Example

• C program invoking printf() library call, which calls write()


system call
Types of System Calls
• Process control
– create process, terminate process
– end, abort
– load, execute
– get process attributes, set process attributes
– wait for time
– wait event, signal event
– allocate and free memory

• Information maintenance (time(), date(), dump(), get process


attributes(), set process attributes())
– get time or date, set time or date
– get system data, set system data
– get and set process, file, or device attributes
Types of System Calls
• File management(create(), delete(), open(), read(), write()), get file
attributes(), set file attributes())
– create file, delete file
– open, close file
– read, write, reposition
• Device management(request(), release(), open(), close(), read(), write(),
reposition()
– request device, release device
– read, write, reposition
– get device attributes, set device attributes
– logically attach or detach devices
• Protection(get permission(),. set permission(), allow user(), deny user(),)
– Control access to resources
– Get and set permissions
– Allow and deny user access
System Programs
• System programs provide a convenient environment for program
development and execution(Editors , Compilers). System programs
can be divided in to 6 categories .
File management - Create, delete, copy, rename, print, list, and
generally manipulate files and directories.
Status information
– Some ask the system for information - date, time, amount of
available memory, disk space, number of users.
– Some systems implement a registry - used to store and retrieve
configuration information.
Application programs
- Run by users
– Not typically considered part of OS.
– Launched by command line, mouse click.
System Programs (Cont.)
File modification
– Text editors to create and modify files.
– Special commands to search contents of files or perform
transformations of the text.
Programming Language Support - Compilers, assemblers,
debuggers and interpreters are used.
Communications - Provide the mechanism for creating virtual
connections among processes, users, and ‘n’ computer systems.
Program loading and Execution

Background Services
– Provide facilities like disk checking, process scheduling, error
logging, printing
– Run in user context not kernel context and also known as
services, subsystems.
Operating System Design and Implementation
• Design and implementation of OS not “solvable”, but some
approaches have proven successful.

• Internal structure of different operating systems can vary widely.


Start the design by defining goals and specifications .

• Affected by the choice of hardware, type of system(batch, single


user, multi user).

• User goals and System goals


– User goals – operating system should be convenient to use,
easy to learn, reliable, safe, and fast
– System goals – operating system should be easy to design,
implement, and maintain, as well as flexible, reliable,
error-free, and efficient.
Operating System Design and Implementation
• Important principle is to separate mechanism and policy.
Policy: What will be done?

Mechanism: How to do something?

• Policies are likely to change across places or over time . Each


change in policy would require a change in mechanism.

• Timer construct is a mechanism for ensuring CPU protection but


deciding how long the timer is to be set for a particular user is a
policy decision.

• Specifying and designing an OS is highly creative task of software


engineering.
Implementation
• Traditionally OS’s have been written in assembly language.
• Master Control Program was the first system that was not written
in assembly language. It is a variant of ALGOL.

• MULTICS developed at MIT was written mainly in PL/1.


• Linux and Windows XP operating system are written in C.

• Use of higher-level language : Code can be written faster, more


compact , easier to understand ,debug and port.
• Emulators are the programs that duplicate the functionality of
one system with another system.

• Disadvantage of implementing in higher language : Reduced speed


and increased storage requirement.
Operating System Structure
MS-DOS (Microsoft Disk Operating System )
• Do not have well defined structure and was written to provide the
most functionality in the least space so not divided into modules.
• Its interfaces and level of functionality are not well separated.

E.g. : Application programs are able to access the basic I/O routine to
write directly to the display . As a result when user program fails
entire system crashes.
BIOS(basic I/O system)
Non Simple Structure -- UNIX
UNIX – limited by hardware functionality, the original UNIX
operating system had limited structuring.
The UNIX OS consists of two separable parts - system programs
and kernel.
Kernel :
•Consists of everything below the system-call interface and
above the physical hardware.
•Provides the file system, CPU scheduling, memory
management, and other operating-system functions, a large
number of functions for one level.
Traditional UNIX System Structure
Beyond simple but not fully layered
Layered Approach
• The operating system is divided into a
number of layers (levels), each built on
top of lower layers. The bottom layer
(layer 0), is the hardware; the highest
(layer N) is the user interface.

• With modularity, layers are selected


such that each uses the functions
(operations) and services of only
lower-level layers.

Layered approach involves defining


the various layers. Because a layer can
use only lower-level layers, hence
careful planning is necessary.
Advantages of Layered Approach
E g : The device driver for the backing store must be at a lower
level than the memory-management routines, because memory
management requires the ability to use the backing store.

Simplicity of construction and debugging : The layers are selected


so that each uses functions and services of only lower level layers.

Simplicity of design and implementation :


• The first layer can be debugged without any concern for the rest
of the system.
• Once the first layer is debugged, its correct functioning can be
assumed while the second layer is debugged, and so on.
• If an error is found during the debugging of a particular layer, the
error must be on that layer, because the layers below it are
already debugged.
Microkernel Approach
Architecture
Microkernel Approach
Advantages
Functionalities can be extended easily
Operating system is easier to port
Provides more security and reliability
Modules Approach(loadable kernel modules.)
Virtual Machines
• The idea behind virtual machine is to abstract the hardware of a
single computer into several different execution environments,
thereby creating the illusion that each separate execution
environment is running its own private computer.
Benefits of virtual machines
• Host system is protected from the virtual machines. A virus inside a
guest operating system might damage that operating system but it
will not affect the host or the other guests.

• Multiple operating systems can be running on the developer's


workstation concurrently .

• Production of data-center use is system consolidation which involves


taking two or more separate systems and running them in virtual
machines on one system.

• A virtual-machine system is a perfect vehicle for operating-systems


research and development.
• A virtual machine is a program that acts as a virtual computer. It runs
on your current operating system – the “host” operating system –
and provides virtual hardware to “guest” operating systems.

• The guest operating systems run in windows on your host operating


system, just like any other program on your computer.

• The guest operating system runs normally, as if it were running on a


physical computer – from the guest operating system’s perspective,
the virtual machine appears to be a real, physical computer.
VM Ware
In this scenario, Linux is running as the host operating system and
FreeBSD, Windows NT, and Windows XP are running as guest
operating systems.

The virtualization layer is the heart of VMware, as it abstracts the


physical hardware into isolated virtual machines running as guest
operating systems.

Each virtual machine has its own virtual CPU, memory, disk drives,
network interfaces, and so forth.
Operating System generation
• The system must then be generated for each specific computer
site, a process sometimes known as SYSGEN.
• SYSGEN program reads from a given file, or asks the operator of
the system for information concerning the specific configuration of
the hardware.
• The following kinds of information must be determined.
What CPU is to be used?
How much memory is available?
How will the boot disk be formatted? How many sections, or
"partitions,“ will it be separated into, and what will go into each
partition?
What operating-system options are desired? how many buffers of
which sizes should be used, what type of CPU-scheduling
algorithm is desired, what the maximum number of processes to
be supported.
CHAPTER 3 PROCESS
Process Concept
• Process – Program in execution; process execution must
progress in sequential fashion.

• Program is passive entity stored on disk (executable file),


process is active entity with a program counter specifying
the next instruction to execute.

– Program becomes process when executable file loaded


into memory.
Process Concept (Cont.)
• Multiple parts
– The program code, also called text section
– Current activity including program counter,
processor registers.
– Stack containing temporary data
• Function parameters, return addresses, local
variables
– Data section containing global variables
– Heap containing memory dynamically allocated
during run time
User and Kernel space
Kernel and Other processes
Process State
• As a process executes, it changes state.
• State of a process is defined as current activity of the process.
– new: The process is being created
– running: Instructions are being executed
– waiting: The process is waiting for some event to occur.
– ready: The process is waiting to be assigned to a processor
– terminated: The process has finished execution.
Threads
• Process is a program that performs a single thread of execution.

• E g : When a process is running a word-processor program, a


single thread of instructions is being executed. This single thread of
control allows the process to perform only one task at a time.

• The user cannot simultaneously type in characters and run the


spell checker within the same process.

• Many modern operating systems have extended the process


concept to allow a process to have multiple threads of execution
and thus to perform more than one task at a time.
Process Control Block (PCB)
• Each process is represented in operating system by a process
control block.
• Process state – running, waiting, etc.
• Program counter – Address of the next instruction to be executed
for this process.
• CPU registers – contents of all process-centric registers.
• CPU scheduling information- Process priority, pointers to
scheduling queues .
• Memory-management information – memory allocated to the
process
• Accounting information – CPU used, clock time elapsed since start,
time limits
• I/O status information – List of I/O devices allocated to process, list
of open files.
CPU Switch From Process to Process

PCB
Process Scheduling
• Multiprogramming :To have some process running at all times.
• Time Sharing : Switch the CPU among processes so frequently
that users can interact with each program while it is running.
• Process scheduler selects among available processes for next
execution on CPU.
• Scheduling queues: As processes enters the system , they are
put in to job queue.
– Job queue – set of all processes in the system
– Ready queue – set of all processes residing in main memory,
ready and waiting to execute are kept on a list.
– Device queues – set of processes waiting for an I/O device.
– Processes migrate among the various queues
Ready Queue

Ready queue is generally stored as a linked list.

A ready-queue header contains pointers to the first and final


PCBs in the list.

Each PCB includes a pointer field that points to the next PCB in
the ready queue.
Representation of Process Scheduling
Queuing diagram :
Each rectangular box represents a queue. The circles represent
the resources that serve the queues.

The arrows indicate the flow of processes in the system.

A new process is initially put in the ready queue. Once the process
is allocated the CPU and is executing, one of several events could
occur.
Schedulers
• Short-term scheduler (CPU scheduler) – selects which process
should be executed next and allocates CPU.
– Short-term scheduler is invoked frequently (milliseconds) ⇒
(must be fast)
• Long-term scheduler (job scheduler) – selects which processes
should be brought into the ready queue.
– Long-term scheduler is invoked 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 – spends more time doing I/O than
computations, many short CPU bursts.(the amount of time the
process uses the processor before it is no longer ready.)
– CPU-bound process – spends more time doing computations,
few very long CPU bursts.
Addition of Medium Term Scheduling
● Medium-term scheduler can be added if degree of multiple
programming needs to decrease.
● Remove process from memory, store on disk, bring back in
from disk to continue execution: swapping
● It is necessary to improve process mix because change in
memory requirements has overcommitted the available
memory requiring memory to be freed up.
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 via a context switch.

• Context of a process represented in the PCB.

• Context-switch time is overhead; the system does no useful work


while switching.
– The more complex the OS and the PCB the longer the
context switch.

• Operations on Process : System must provide mechanisms for


– process creation
– process termination
Process Creation
• Parent process create children processes, which, in turn create
other processes, forming a tree of processes.

• Generally, process identified and managed via a process


identifier (pid).

• Resource sharing options


– Parent and children share all resources.
– Children share subset of parents resources.

• Execution options
– Parent and children execute concurrently.
– Parent waits until children terminates.
• 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.
Process Creation (Cont.)
Address space
• The child process is a duplicate of the parent process (it has the
same program and data as the parent).
• The child process has a new 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.
C Program Forking Separate Process
Process Termination
• Process executes last statement and then asks the operating
system to delete it using the exit() system call.
– Returns status data from child to parent (via wait())
– Process resources are deallocated by operating system.

• Parent may terminate the execution of children processes using


the abort() system call. Some reasons for doing so:
– Child has exceeded allocated resources.
– Task assigned to child is no longer required.
– The parent is exiting and the operating system does not allow
a child to continue if its parent terminates.
Process Termination
• Some operating systems do not allow child to exists if its parent has
terminated. If a process terminates, then all its children must also be
terminated.
– cascading termination : All children, grandchildren, etc. are terminated.
– The termination is initiated by the operating system.
• The parent process may wait for termination of a child process by using the
wait()system call.The call returns status information and the pid of the
terminated process
pid = wait(&status);

• If parent is waiting ( invoke wait()) process is a zombie.


( zombie process or defunct process is a process that has completed execution (via
the exit system call) but still has an entry in the process table: it is a process in
the "Terminated state".)
• If parent terminated without invoking wait , process is an orphan.
Interprocess Communication
• Processes within a system may be independent or cooperating.

• Cooperating process can affect or be affected by other processes,


including sharing data.

• Independent process cannot affect or be affected by the execution


of another process.

• Cooperating processes need interprocess communication (IPC)

• Two models of IPC


– Shared memory
– Message passing
Cooperating Processes
Advantages of process cooperation
• Information sharing :Several users want to access same piece of
information (Eg: a shared file), we must provide an environment to
allow concurrent access to such information.

• Computation speed-up: If we want a particular task to run faster,


we must break it into subtasks, each of which will be executing in
parallel with the others.

• Modularity: We may want to construct the system in a modular


fashion, dividing the system functions into separate
processes/threads.

• Convenience :An individual user may work on many tasks at the


same time.
Communications Models
Message Passing : Communication takes place by means of
messages exchanged between the cooperating process.

Shared Memory : A region of memory is shared among the


cooperating process . Process can then exchange information by
reading and writing data to shared region.
Shared Memory : Producer-Consumer Problem
• Producer and consumer processes to run concurrently, we must
have available a buffer of items that can be filled by the producer
and emptied by the consumer.

• The buffer will reside in a region of memory that is shared by the


producer and consumer processes. A producer can produce one
item while the consumer is consuming another item.

• The producer and consumer must be synchronized, so that the


consumer does not try to consume an item that has not yet been
produced.
Bounded-Buffer – Shared-Memory Solution
• 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.
• Shared data
#define BUFFER_SIZE 10
typedef struct {
...
} item;

item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
Bounded-Buffer – Producer

item next_produced;
while (true) {
/* produce an item in next produced */
while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
}
Bounded Buffer – Consumer

item next_consumed;
while (true) {
while (in == out)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;

/* consume the item in next consumed */


}
Message Passing
• If processes P and Q wish to communicate, they need to:
– Establish a communication link between them.
– Exchange messages via send/receive.

• Implementation issues:
– How are links established?
– Can a link be associated with more than two processes?
– How many links can there be between every pair of
communicating processes?
– What is the capacity of a link?
– Is the size of a message that the link can accommodate fixed
or variable?
– Is a link unidirectional or bi-directional?
Message Passing (Cont.)

• Implementation of communication link


– Physical:
• Shared memory
• Hardware bus
• Network
– Logical:
• Direct or indirect
• Synchronous or asynchronous
• Automatic or explicit buffering
Direct Communication
• Processes must name each other explicitly:
– send (P, message) – send a message to process P
– receive(Q, message) – receive a message from
process Q
• 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
Indirect Communication

• Operations
– create a new mailbox (port)
– 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
Indirect Communication
• 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 arbitarily the receiver. Sender is
notified who the receiver was.
Synchronization
• Message passing may be either blocking or non-blocking.

• Blocking is considered synchronous.


– Blocking send -- the sender is blocked until the message is
received
– Blocking receive -- the receiver is blocked until a message is
available.

• Non-blocking is considered asynchronous.


– Non-blocking send -- the sender sends the message and
continue.
– Non-blocking receive -- the receiver receives:
● A valid message, or Null message
Buffering
• Whether communication is direct or indirect, messages exchanged
by communicating processes reside in a temporary queue.
• Implemented in one of three ways
1.Zero capacity – Queue has maximum length zero. Sender must
block until recipient receives the message.

2.Bounded capacity – finite length of n messages. If the queue is not


full when a new message is sent, the message is placed in the
queue and the sender can continue execution without waiting.

3.Unbounded capacity – infinite length .Any number of messages can


wait in it. The sender never blocks.

You might also like