118
7/24/2019 OS Study Material http://slidepdf.com/reader/full/os-study-material 1/118 Operating System Gate Syllabus:  Weightage of marks 1 Mark 2 Mark Total marks 1-3 2-8 4-17 INTRODUCTION: An OS is a program which acts as an interface between computer system users and the computer hardware. It provides a user-friendly environment in which a user may easily develop and execute programs. Otherwise, hardware knowledge would be mandatory for computer programming. So, it can be said that an OS hides the complexity of hardware from uninterested users. In general, a computer system has some resources which may be utilied to solve a problem.  !hey are " #emory  " $rocessor%s&  " I'O " (ile System etc.

OS Study Material

Embed Size (px)

Citation preview

Page 1: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 1/118

Operating System Gate Syllabus:

 Weightage of marks

1 Mark 2 Mark Total marks1-3 2-8 4-17

INTRODUCTION:

An OS is a program which acts as an interface between computer system users and

the computer hardware. It provides a user-friendly environment in which a user may

easily develop and execute programs. Otherwise, hardware knowledge would be

mandatory for computer programming. So, it can be said that an OS hides thecomplexity of hardware from uninterested users.

In general, a computer system has some resources which may be utilied to solve a

problem.

 !hey are

" #emory

  " $rocessor%s&

  " I'O

" (ile System etc.

Page 2: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 2/118

 !he OS manages these resources and allocates them to speci)c programs and

users. *ith the management of the OS, a programmer is rid of di+cult hardware

considerations. An OS provides services for

" $rocessor #anagement

" #emory #anagement

" (ile #anagement

 " evice #anagement

" oncurrency ontrol

What is an Operating System?The 1960’s definition of an operating system is “the software that controls the

hardware”. However, today, de to microcode we need a !etter definition. "e see anoperating system as the programs that ma#e the hardware sea!le. $n !rief, an

operating system is the set of programs that controls a compter. %ome e&amples of 

operating systems are '($), *ach, *%+-%, *%+"indows, "indows(T, /hicago,

-%, *ac-%, *%, *%, and *.

/ontrolling the compter involves software at several levels. "e will differentiate

#ernel services, li!rary services, and application+level services, all of which are part of 

the operating system. 2rocesses rn 3pplications, which are lin#ed together with

li!raries that perform standard services. The #ernel spports the processes !y

 providing a path to the peripheral devices. The #ernel responds to service calls from

the processes and interrpts from the devices. The core of the operating system is the

#ernel, a control program that fnctions in privileged state 4an e&ection conte&t that

allows all hardware instrctions to !e e&ected5, reacting to interrpts from e&ternal

devices and to service reests and traps from processes. 7enerally, the #ernel is a

 permanent resident of the compter. $t creates and terminates processes and responds

to their reest for service.

-perating %ystems are resorce managers. The main resorce is compter hardware in

the form of processors, storage, inptotpt devices, commnication devices, anddata. %ome of the operating system fnctions are8 implementing the ser interface,

sharing hardware among sers, allowing sers to share data among themselves,

 preventing sers from interfering with one another, schedling resorces among sers,

facilitating inptotpt, recovering from errors, acconting for resorce sage,

Page 3: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 3/118

facilitating parallel operations, organiing data for secre and rapid access, and

handling networ# commnications.

Objecties !" Operating Systems

*odern -perating systems generally have following three ma:or goals. -perating

systems generally accomplish these goals !y rnning processes in low privilege and

 providing service calls that invo#e the operating system #ernel in high+privilege state.

• T! hi#e #etails !" har#$are by creating abstracti!n

An abstraction is software that hides lower level details andprovides a set of higher-level functions. An operating system

transforms the physical world of devices, instructions, memory,and time into virtual world that is the result of abstractionsbuilt by the operating system. !here are several reasons forabstraction.First , the code needed to control peripheral devices is notstandardied. Operating systems provide subroutines calleddevice drivers that perform operations on behalf of programsfor example, input'output operations.

Second, the operating system introduces new functions as itabstracts the hardware. (or instance, operating systemintroduces the )le abstraction so that programs do not have todeal with disks.

Third, the operating system transforms the computer hardwareinto multiple virtual computers, each belonging to a dierentprogram. /ach program that is running is called a process./ach process views the hardware through the lens of

abstraction.Fourth, the operating system can enforce security throughabstraction.

T! all!cate res!urces t! pr!cesses %&anage res!urces'An operating system controls how pr!cesses %the active

Page 4: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 4/118

agents& may access res!urces %passive entities&. 

• (r!i#e a pleasant an# e)ectie user inter"ace !he user interacts with the operating systems through the userinterface and usually interested in the 0look and feel1 of theoperating system. !he most important components of the userinterface are the command interpreter, the )le system, on-linehelp, and application integration. !he recent trend has beentoward increasingly integrated graphical user interfaces thatencompass the activities of multiple processes on networks ofcomputers.

-ne can view -perating %ystems from two points of views8

 Resource manager and Extended machines.

 ;orm <esorce manager point of view -perating %ystems manage the different parts

of the system efficiently and from e&tended machines point of view -perating

%ystems provide a virtal machine to sers that is more convenient to se. The

strctrally -perating %ystems can !e design as a monolithic system, a hierarchy of 

layers, a virtal machine system, an e&o#ernel, or sing the client+server model. The

 !asic concepts of -perating %ystems are processes, memory management, $-

management, the file systems, and secrity.

Historically operating systems have !een tightly related to the compter architectre,

it is good idea to stdy the history of operating systems from the architectre of the

compters on which they rn.

-perating systems have evolved throgh a nm!er of distinct phases or generations

which corresponds roghly to the decades.

 !he 23456s - (irst 7enerations

The earliest electronic digital compters had no operating systems. *achines of the

time were so primitive that programs were often entered one !it at time on rows of

mechanical switches 4plg !oards5. 2rogramming langages were n#nown 4not even

assem!ly langages5. -perating systems were nheard of .

Page 5: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 5/118

 !he 23856s - Second 7eneration

=y the early 19>0?s, the rotine had improved somewhat with the introdction of

 pnch cards. The 7eneral *otors <esearch @a!oratories implemented the first

operating systems in early 19>0?s for their $=* A01. The system of the >0?s generally

ran one :o! at a time. These were called single+stream !atch processing systems

 !ecase programs and data were s!mitted in grops or !atches.

 !he 23956s - !hird 7eneration

The systems of the 1960?s were also !atch processing systems, !t they were a!le to

ta#e !etter advantage of the compter?s resorces !y rnning several :o!s at once. %o

operating systems designers developed the concept of mltiprogramming in which

several :o!s are in main memory at onceB a processor is switched from :o! to :o! as

needed to #eep several :o!s advancing while #eeping the peripheral devices in se.

;or e&ample, on the system with no mltiprogramming, when the crrent :o! pasedto wait for other $- operation to complete, the /2' simply sat idle ntil the $-

finished. The soltion for this pro!lem that evolved was to partition memory into

several pieces, with a different :o! in each partition. "hile one :o! was waiting for

$- to complete, another :o! cold !e sing the /2'.

3nother ma:or featre in third+generation operating system was the technie called

spooling 4simltaneos peripheral operations on line5. $n spooling, a high+speed

device li#e a dis# interposed !etween a rnning program and a low+speed device

involved with the program in inptotpt. $nstead of writing directly to a printer, fore&ample, otpts are written to the dis#. 2rograms can rn to completion faster, and

other programs can !e initiated sooner when the printer !ecomes availa!le, the

otpts may !e printed.

 (ote that spooling technie is mch li#e thread !eing spn to a spool so that it may

 !e later !e nwond as needed.

3nother featre present in this generation was time+sharing technie, a variant of

mltiprogramming technie, in which each ser has an on+line 4i.e., directly

connected5 terminal. =ecase the ser is present and interacting with the compter, thecompter system mst respond ic#ly to ser reests, otherwise ser prodctivity

cold sffer. Timesharing systems were developed to mltiprogram large nm!er of

simltaneos interactive sers.

Page 6: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 6/118

(ourth 7eneration

"ith the development of @%$ 4@arge %cale $ntegration5 circits, chips, operating

system entered in the system entered in the personal compter and the wor#station

age. *icroprocessor technology evolved to the point that it !ecome possi!le to !ild

des#top compters as powerfl as the mainframes of the 19A0s. Two operating

systems have dominated the personal compter scene8 *%+-%, written !y

*icrosoft, $nc. for the $=* 2/ and other machines sing the $ntel C0CC /2' and its

sccessors, and '($), which is dominant on the large personal compters sing the

*otorola 6C99 /2' family.

System C!mp!nents

Dven thogh, not all systems have the same strctre many modern operating systems

share the same goal of spporting the following types of system components.

 

(r!cess &anagementThe operating system manages many #inds of activities ranging from ser programs to

system programs li#e printer spooler, name servers, file server etc. Dach of these

activities is encapslated in a process. 3 process incldes the complete e&ection

conte&t 4code, data, 2/, registers, -% resorces in se etc.5.

$t is important to note that a process is not a program. 3 process is only -(D instantof a program in e&ection. There are many processes can !e rnning the same

 program. The five ma:or activities of an operating system in regard to process

management are

• reation and deletion of user and system processes.

• Suspension and resumption of processes.

A mechanism for process synchroniation.

• A mechanism for process communication.

• A mechanism for deadlock handling.

Page 7: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 7/118

 

#ain-#emory #anagement

2rimary+*emory or *ain+*emory is a large array of words or !ytes. Dach word or

 !yte has its own address. *ain+memory provides storage that can !e access directly !y the /2'. That is to say for a program to !e e&ected, it mst in the main memory.

The ma:or activities of an operating in regard to memory+management are8

• :eep track of which part of memory are currently being used

and by whom.

• ecide which process are loaded into memory when memory

space becomes available.

• Allocate and deallocate memory space as needed.

 

(ile #anagement

3 file is a collected of related information defined !y its creator. /ompter can store

files on the dis# 4secondary storage5, which provide long term storage. %ome

e&amples of storage media are magnetic tape, magnetic dis# and optical dis#. Dach of

these media has its own properties li#e speed, capacity, data transfer rate and access

methods.

3 file systems normally organied into directories to ease their se. These directories

may contain files and other directions.

The five main ma:or activities of an operating system in regard to file management are

2. !he creation and deletion of )les.

;. !he creation and deletion of directions.

<. !he support of primitives for manipulating )les and directions.

4. !he mapping of )les onto secondary storage.

8. !he back up of )les on stable storage media.

Page 8: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 8/118

 

I'O System #anagement

$- s!system hides the pecliarities of specific hardware devices from the ser. -nly

the device driver #nows the pecliarities of the specific device to whom it is assigned.

 

Secondary-Storage #anagement

7enerally spea#ing, systems have several levels of storage, inclding primary storage,

secondary storage and cache storage. $nstrctions and data mst !e placed in primary

storage or cache to !e referenced !y a rnning program. =ecase main memory is too

small to accommodate all data and programs, and its data are lost when power is lost,

the compter system mst provide secondary storage to !ac# p main memory.

%econdary storage consists of tapes, dis#s, and other media designed to hold

information that will eventally !e accessed in primary storage 4primary, secondary,

cache5 is ordinarily divided into !ytes or words consisting of a fi&ed nm!er of !ytes.

Dach location in storage has an addressB the set of all addresses availa!le to a program

is called an address space.

The three ma:or activities of an operating system in regard to secondary storage

management are8

2. #anaging the free space available on the secondary-storagedevice.

;. Allocation of storage space when new )les have to be written.

<. Scheduling the re=uests for memory access.

 

>etworking

3 distri!ted systems is a collection of processors that do not share memory, peripheral devices, or a cloc#. The processors commnicate with one another throgh

commnication lines called networ#. The commnication+networ# design mst

consider roting and connection strategies, and the pro!lems of contention and

secrity.

Page 9: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 9/118

 

$rotection System

$f a compter systems has mltiple sers and allows the concrrent e&ection of

mltiple processes, then the varios processes mst !e protected from one another?sactivities. 2rotection refers to mechanism for controlling the access of programs,

 processes, or sers to the resorces defined !y a compter systems.

 

ommand Interpreter System

3 command interpreter is an interface of the operating system with the ser. The ser

gives commands with are e&ected !y operating system 4sally !y trning them into

system calls5. The main fnction of a command interpreter is to get and e&ecte the

ne&t ser specified command. /ommand+$nterpreter is sally not part of the #ernel,

since mltiple command interpreters 4shell, in '($) terminology5 may !e spport !y

an operating system, and they do not really need to rn in #ernel mode. There are two

main advantages to separating the command interpreter from the #ernel.

2. If we want to change the way the command interpreter looks,i.e., I want to change the interface of command interpreter, Iam able to do that if the command interpreter is separate fromthe kernel. I cannot change the code of the kernel so I cannot

modify the interface.

;. If the command interpreter is a part of the kernel it is possiblefor a malicious process to gain access to certain part of thekernel that it showed not have to avoid this ugly scenario it isadvantageous to have the command interpreter separate fromkernel.

 

Operating System Services

;ollowing are the five services provided !y an operating systems to the convenience of the sers.

Page 10: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 10/118

$rogram /xecution

The prpose of a compter systems is to allow the ser to e&ecte programs. %o the operating

systems provides an environment where the ser can conveniently rn programs. The ser does

not have to worry a!ot the memory allocation or mltitas#ing or anything. These things are

ta#en care of !y the operating systems.

<nning a program involves the allocating and deallocating memory, /2' schedling in case of

mltiprocess. These fnctions cannot !e given to the ser+level programs. %o ser+level programs

cannot help the ser to rn programs independently withot the help from operating systems.

 

I'O Operations

Dach program reires an inpt and prodces otpt. This involves the se of $-. The operating

systems hides the ser the details of nderlying hardware for the $-. 3ll the ser sees is that the

$- has !een performed withot any details. %o the operating systems !y providing $- ma#es itconvenient for the sers to rn programs.

;or efficiently and protection sers cannot control $- so this service cannot !e provided !y ser+

level programs.

 

(ile System #anipulation

The otpt of a program may need to !e written into new files or inpt ta#en from some files.

The operating systems provides this service. The ser does not have to worry a!ot secondarystorage management. 'ser gives a command for reading or writing to a file and sees his her tas# 

accomplished. Ths operating systems ma#es it easier for ser programs to accomplished their 

tas#.

This service involves secondary storage management. The speed of $- that depends on

secondary storage management is critical to the speed of many programs and hence $ thin# it is

 !est relegated to the operating systems to manage it than giving individal sers the control of it.

$t is not difficlt for the ser+level programs to provide these services !t for a!ove mentioned

reasons it is !est if this service s left with operating system.

 

ommunications

There are instances where processes need to commnicate with each other to e&change

information. $t may !e !etween processes rnning on the same compter or rnning on the

different compters. =y providing this service the operating system relieves the ser of the worry

Page 11: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 11/118

of passing messages !etween processes. $n case where the messages need to !e passed to

 processes on the other compters throgh a networ# it can !e done !y the ser programs. The

ser program may !e cstomied to the specifics of the hardware throgh which the message

transits and provides the service interface to the operating system.

 

/rror etection

3n error is one part of the system may case malfnctioning of the complete system. To avoid

sch a sitation the operating system constantly monitors the system for detecting the errors.

This relieves the ser of the worry of errors propagating to varios part of the system and

casing malfnctioning.

This service cannot allowed to !e handled !y ser programs !ecase it involves monitoring and

in cases altering area of memory or deallocation of memory for a falty process. -r may !e

relinishing the /2' of a process that goes into an infinite loop. These tas#s are too critical to !e handed over to the ser programs. 3 ser program if given these privileges can interfere with

the correct 4normal5 operation of the operating systems.

 

System alls and System $rograms

 

%ystem calls provide an interface !etween the process an the operating system.

%ystem calls allow ser+level processes to reest some services from the operating

system which process itself is not allowed to do. $n handling the trap, the operating

system will enter in the #ernel mode, where it has access to privileged instrctions,

and can perform the desired service on the !ehalf of ser+level process. $t is !ecase

of the critical natre of operations that the operating system itself does them every

time they are needed. ;or e&ample, for $- a process involves a system call telling the

operating system to read or write particlar area and this reest is satisfied !y theoperating system.

%ystem programs provide !asic fnctioning to sers so that they do not need to write

their own environment for program development 4editors, compilers5 and program

e&ection 4shells5. $n some sense, they are !ndles of sefl system calls.

Page 12: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 12/118

operating system structure:

An operating system might have many structure. According to the structure of the operating

system; operating systems can be classified into many categories.

Some of the main structures used in operating systems are:

1. Monolithic architecture of operating system

Page 13: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 13/118

monolithic sturucture of operating system

It is the oldest architecture used for developing operating system. Operating system resides

on kernel for anyone to execute. System call is involved i.e. Sitching from user mode to

kernel mode and transfer control to operating system shon as event 1. !any "#$ has to

modes% kernel mode% for the operating system in hich all instruction are alloed and user

mode for user program in hich I&O devices and certain other instruction are not alloed.

'o operating system then examines the parameter of the call to determine hich system

call is to be carried out shon in event (. )ext% the operating system index*s into a table

that contains procedure that carries out system call. 'his operation is shon in events.

+inally% it is called hen the ork has been completed and the system call is finished%

control is given back to the user mode as shon in event ,.

(. Layered Architecture of operating system

'he layered Architecture of operating system as developed in -*s in this approach; the

operating system is broken up into number of layers. 'he bottom layer /layer 0 is the

hardare layer and the highest layer /layer n0 is the user interface layer as shon in thefigure.

Page 14: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 14/118

layered architecture

'he layered are selected such that each user functions and services of only loer level layer.

'he first layer can be debugged it out any concern for the rest of the system. It user basic

hardare to implement this function once the first layer is debugged.% it*s correct functioning

can be assumed hile the second layer is debugged soon . If an error is found during the

debugged of particular layer% the layer must be on that layer% because the layer belo it

already debugged. 2ecause of this design of the system is simplified hen operating system

is broken up into layer.

Os&( operating system is example of layered architecture of operating system another

example is earlier version of 3indos )'.

'he main disadvantage of this architecture is that it re4uires an appropriate definition of the

various layers a careful planning of the proper placement of the layer.

5. Virtual memory architecture of operating system

virtual memory architecture

6irtual machine is an illusion of a real machine. It is created by a real machine operating

system% hich make a single real machine appears to be several real machine. 'he

architecture of virtual machine is shon above.

'he best example of virtual machine architecture is I2! 57 computer. In this system each

Page 15: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 15/118

user can choose a different operating system. Actually% virtual machine can run several

operating systems at once% each of them on its virtual machine.

Its multiprogramming shares the resource of a single machine in different manner.

'he concepts of virtual machine are:8

a. "ontrol program /cp0:8 cp creates the environment in hich virtual machine can execute.

It gives to each user facilities of real machine such as processor% storage I& devices.2. conversation monitor system /cons0:8 cons is a system application having features of

developing program. It contains editor% language translator% and various application

packages.

c. 9emote spooling communication system /9S"S0:8 provide virtual machine ith the

ability to transmit and receive file in distributed system.

d. I#"S /interactive problem control system0:8 it is used to fix the virtual machine softare

problems.

,. client/server architecture of operating system

A trend in modern operating system is to move maximum code into the higher level and

remove as much as possible from operating system% minimising the ork of the kernel. 'he

basic approach is to implement most of the operating system functions in user processes to

re4uest a service% such as re4uest to read a particular file% user send a re4uest to the server

process% server checks the parameter and finds hether it is valid or not% after that server

does the ork and send back the anser to client server model orks on re4uest8 response

techni4ue i.e. "lient alays send re4uest to the side in order to perform the task% and on

the other side% server gates complementing that re4uest send back response. 'he figure

belo shos client server architecture.

client server model

In this model% the main task of the kernel is to handle all the communication beteen the

client and the server by splitting the operating system into number of ports% each of hich

only handle some specific task. I.e. file server% process server% terminal server and memory

service.

Another advantage of the client8server model is it*s adaptability to user in distributedsystem. If the client communicates ith the server by sending it the message% the client

need not kno hether it as send a . Is the netork to a server on a remote machine

As in case of client% same thing happen and occurs in client side that is a re4uest as send

and a reply come back.

 

Page 16: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 16/118

(ROC*SS &+N+G*&*N*NT

The term EprocessE was first sed !y the designers of the *'@T$/% in 1960?s. %ince

then, the term process, sed somewhat interchangea!ly with ?tas#? or ?:o!?. The process

has !een given many definitions for instance

• 3 program in D&ection.

• 3n asynchronos activity.

• The ?animated sprit? of a procedre in e&ection.

• The entity to which processors are assigned.

• The ?dispatcha!le? nit.

and many more definitions have given. 3s we can see from a!ove that there is no

niversally agreed pon definition, !t the definition E Program in ExecutionE seem to !e most freently sed. 3nd this is a concept are will se in the present stdy of

operating systems.

 (ow that we agreed pon the definition of process, the estion is what is the relation

 !etween process and program. $t is same !east with different name or when this !east

is sleeping 4not e&ecting5 it is called program and when it is e&ecting !ecomes

 process. "ell, to !e very precise. 2rocess is not the same as program. $n the following

discssion we point ot some of the difference !etween process and program. 3s we

have mentioned earlier.

2rocess is not the same as program. 3 process is more than a program code. 3 process

is an ?active? entity as oppose to program which consider to !e a ?passive? entity. 3s we

all #now that a program is an algorithm e&pressed in some sita!le notation, 4e.g.,

 programming langage5. =eing a passive, a program is only a part of process. 2rocess,

on the other hand, incldes8

Page 17: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 17/118

• /rrent vale of 2rogram /onter 42/5

• /ontents of the processors registers

• ale of the varia!les

• The process stac# 4%25 which typically contains temporary data sch as

s!rotine parameter, retrn address, and temporary varia!les.

• 3 data section that contains glo!al varia!les.

3 process is the nit of wor# in a system.

$n 2rocess model, all software on the compter is organied into a nm!er of

seential processes. 3 process incldes 2/, registers, and varia!les. /onceptally,each process has its own virtal /2'. $n reality, the /2' switches !ac# and forth

among processes. 4The rapid switching !ac# and forth is called mltiprogramming5.

A process is a program in execution. 'he execution of a process must

progress in a se4uential fashion. <efinition of process is folloing.

• A process is defined as an entity hich represents the basic unit of ork to be

implemented in the system.

"omponents of process are folloing.

S.N. Component & Description

1 !"ect #rogram

"ode to be executed.

( Data

<ata to be used for executing the program.

5 $esources

3hile executing the program% it may re4uire some resources.

, Status

Page 18: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 18/118

6erifies the status of the process execution.A process can run

to completion only hen all re4uested resources have been

allocated to the process. 'o or more processes could be

executing the same program% each using their on data and

resources.

#rogram

A program by itself is not a process. It is a static entity made up of program

statement hile process is a dynamic entity. #rogram contains the

instructions to be executed by processor.

A program takes a space at single place in main memory and continues to

stay there. A program does not perform any action by itself.

#rocess States

As a process executes% it changes state. 'he state of a process is defined as

the current activity of the process.

#rocess can have one of the folloing five states at a time.

S.N. State & Description

1 Ne%

'he process is being created.

( $eady

'he process is aiting to be assigned to a processor. 9eady

processes are aiting to have the processor allocated to

them by the operating system so that they can run.

5 $unning

#rocess instructions are being executed /i.e. 'he process that

is currently being executed0.

, aiting

Page 19: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 19/118

'he process is aiting for some event to occur /such as the

completion of an I&O operation0.

= 'erminated

'he process has finished execution.

#rocess Control (loc)* #C(

>ach process is represented in the operating system by a process control

block /#"20 also called a task control block. #"2 is the data structure usedby the operating system. Operating system groups all information that

needs about particular process.

#"2 contains many pieces of information associated ith a specific process

hich are described belo.

S.N. +nformation & Description

1 #ointer

#ointer points to another process control block. #ointer is

used for maintaining the scheduling list.

( #rocess State

Page 20: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 20/118

#rocess state may be ne% ready% running% aiting and so on.

5 #rogram Counter

#rogram "ounter indicates the address of the next instruction

to be executed for this process.

, C#, registers

"#$ registers include general purpose register% stack

pointers% index registers and accumulators etc. number of

register and type of register totally depends upon the

computer architecture.

= Memory management information

'his information may include the value of base and limitregisters% the page tables% or the segment tables depending

on the memory system used by the operating system.'his

information is useful for deallocating the memory hen the

process terminates.

- Accounting information

'his information includes the amount of "#$ and real time

used% time limits% ?ob or process numbers% account numbers

etc.

Page 21: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 21/118

#rocess control block includes "#$ scheduling% I&O resource management%

file management information etc.. 'he #"2 serves as the repository for any

information hich can vary from process to process. @oader&linker sets flags

and registers hen a process is created. If that process get suspended% the

contents of the registers are saved on a stack and the pointer to theparticular stack frame is stored in the #"2. 2y this techni4ue% the hardare

state can be restored so that the process can be scheduled to run again.

'he process scheduling is the activity of the process manager that handles

the removal of the running process from the "#$ and the selection of 

another process on the basis of a particular strategy.

#rocess scheduling is an essential part of a !ultiprogramming operating

system. Such operating systems allo more than one process to be loadedinto the executable memory at a time and loaded process shares the "#$

using time multiplexing.

Page 22: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 22/118

Scheduling -ueues

Scheduling 4ueues refers to 4ueues of processes or devices. 3hen the

process enters into the system% then this process is put into a ?ob 4ueue.

'his 4ueue consists of all processes in the system. 'he operating system

also maintains other 4ueues such as device 4ueue. <evice 4ueue is a 4ueue

for hich multiple processes are aiting for a particular I&O device. >ach

device has its on device 4ueue.

'his figure shos the 4ueuing diagram of process scheduling.

• ueue is represented by rectangular box.

• 'he circles represent the resources that serve the 4ueues.

• 'he arros indicate the process flo in the system.

ueues are of to types

Page 23: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 23/118

• 9eady 4ueue

• <evice 4ueue

A nely arrived process is put in the ready 4ueue. #rocesses aits in ready4ueue for allocating the "#$. Once the "#$ is assigned to a process% then

that process ill execute. 3hile executing the process% any one of the

folloing events can occur.

• 'he process could issue an I&O re4uest and then it ould be placed in an I&O

4ueue.

• 'he process could create ne sub process and ill ait for its termination.

• 'he process could be removed forcibly from the "#$% as a result of interrupt and

put back in the ready 4ueue.

'%o State #rocess Model

'o state process model refers to running and non8running states hich are

described belo.

S.N. State & Description

1 $unning

3hen ne process is created by Operating System that

process enters into the system as in the running state.

( Not $unning

#rocesses that are not running are kept in 4ueue% aiting for

their turn to execute. >ach entry in the 4ueue is a pointer to

a particular process. ueue is implemented by using linkedlist. $se of dispatcher is as follos. 3hen a process is

interrupted% that process is transferred in the aiting 4ueue.

If the process has completed or aborted% the process is

discarded. In either case% the dispatcher then selects a

process from the 4ueue to execute.

Page 24: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 24/118

Schedulers

Schedulers are special system softares hich handles process scheduling

in various ays.'heir main task is to select the ?obs to be submitted into

the system and to decide hich process to run. Schedulers are of three

types

• @ong 'erm Scheduler

• Short 'erm Scheduler

• !edium 'erm Scheduler

Long 'erm Scheduler

It is also called ?ob scheduler. @ong term scheduler determines hich

programs are admitted to the system for processing. Bob scheduler selects

processes from the 4ueue and loads them into memory for execution.

#rocess loads into the memory for "#$ scheduling. 'he primary ob?ective of 

the ?ob scheduler is to provide a balanced mix of ?obs% such as I&O bound

and processor bound. It also controls the degree of multiprogramming. If 

the degree of multiprogramming is stable% then the average rate of process

creation must be e4ual to the average departure rate of processes leaving

the system.

On some systems% the long term scheduler may not be available or minimal.

'ime8sharing operating systems have no long term scheduler. 3hen process

changes the state from ne to ready% then there is use of long term

scheduler.

Short 'erm SchedulerIt is also called "#$ scheduler. !ain ob?ective is increasing system

performance in accordance ith the chosen set of criteria. It is the change

of ready state to running state of the process. "#$ scheduler selects

Page 25: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 25/118

process among the processes that are ready to execute and allocates "#$

to one of them.

Short term scheduler also knon as dispatcher% execute most fre4uently

and makes the fine grained decision of hich process to execute next. Shortterm scheduler is faster than long term scheduler.

Medium 'erm Scheduler

!edium term scheduling is part of the sapping. It removes the processes

from the memory. It reduces the degree of multiprogramming. 'he medium

term scheduler is in8charge of handling the sapped out8processes.

9unning process may become suspended if it makes an I&O re4uest.

Suspended processes cannot make any progress toards completion. In

this condition% to remove the process from memory and make space for

other process% the suspended process is moved to the secondary storage.

'his process is called sapping% and the process is said to be sapped out

or rolled out. Sapping may be necessary to improve the process mix.

Comparison !et%een SchedulerS.N. Long 'erm

Scheduler

Short 'erm

Scheduler

Medium 'erm

Scheduler

Page 26: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 26/118

1 It is a ?ob

scheduler

It is a "#$

scheduler

It is a process

sapping

scheduler.

( Speed is lesserthan short term

scheduler

Speed is fastestamong other to

Speed is inbeteen both short

and long term

scheduler.

5 It controls the

degree of

multiprogramming

It provides lesser

control over

degree of

multiprogramming

It reduces the

degree of

multiprogramming.

, It is almost absent

or minimal in time

sharing system

It is also minimal

in time sharing

system

It is a part of 'ime

sharing systems.

= It selects

processes from

pool and loads

them into memory

for execution

It selects those

processes hich

are ready to

execute

It can re8introduce

the process into

memory and

execution can be

continued.

Contet S%itch

A context sitch is the mechanism to store and restore the state or context

of a "#$ in #rocess "ontrol block so that a process execution can be

resumed from the same point at a later time. $sing this techni4ue a context

sitcher enables multiple processes to share a single "#$. "ontext

sitching is an essential part of a multitasking operating system features.

3hen the scheduler sitches the "#$ from executing one process to

execute another% the context sitcher saves the content of all processor

registers for the process being removed from the "#$% in its process

descriptor. 'he context of a process is represented in the process control

block of a process.

Page 27: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 27/118

"ontext sitch time is pure overhead. "ontext sitching can significantly

affect performance as modern computers have a lot of general and status

registers to be saved. "ontent sitching times are highly dependent on

hardare support. "ontext sitch re4uires / n C m 0 bxD time units to save

the state of the processor ith n general registers% assuming b are the store

operations are re4uired to save n and m registers of to process control

blocks and each store instruction re4uires D time units.

Some hardare systems employ to or more sets of processor registers to

reduce the amount of context sitching time. 3hen the process is sitched%

the folloing information is stored.

#rogram "ounter

• Scheduling Information

• 2ase and limit register value

• "urrently used register

Page 28: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 28/118

• "hanged State

• I&O State

Accounting

3eEll discuss four ma?or scheduling algorithms here hich are folloing

• +irst "ome +irst Serve /+"+S0 Scheduling

• Shortest8Bob8+irst /SB+0 Scheduling

• #riority Scheduling

• 9ound 9obin/990 Scheduling

• !ultilevel ueue Scheduling

irst Come irst Serve 0CS1

• Bobs are executed on first come% first serve basis.

• >asy to understand and implement.

• #oor in performance as average ait time is high.

Page 29: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 29/118

3ait time of each process is folloing

#rocess ait 'ime 2 Service 'ime 3 Arrival 'ime

# 8 F

#1 = 8 1 F ,

#( G 8 ( F -

#5 1- 8 5 F 15

Average 3ait 'ime: /C,C-C150 & , F =.==

Shortest 4o! irst 0S41

• 2est approach to minimiHe aiting time.

• Impossible to implement

• #rocesser should kno in advance ho much time process ill take.

Page 30: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 30/118

3ait time of each process is folloing

#rocess ait 'ime 2 Service 'ime 3 Arrival 'ime

# 5 8 F 5

#1 8 F

#( 1- 8 ( F 1,

#5 G 8 5 F =

Average 3ait 'ime: /5CC1,C=0 & , F =.=

#riority (ased Scheduling

• >ach process is assigned a priority. #rocess ith highest priority is to be

executed first and so on.

#rocesses ith same priority are executed on first come first serve basis.

• #riority can be decided based on memory re4uirements% time re4uirements or

any other resource re4uirement.

Page 31: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 31/118

3ait time of each process is folloing

#rocess ait 'ime 2 Service 'ime 3 Arrival 'ime

# 8 F

#1 - 8 1 F =

#( 1, 8 ( F 1(

#5 8 F

Average 3ait 'ime: /C=C1(C0 & , F -.=

$ound $o!in Scheduling• >ach process is provided a fix time to execute called 4uantum.

• Once a process is executed for given time period. #rocess is preempted and

other process executes for given time period.

Page 32: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 32/118

• "ontext sitching is used to save states of preempted processes.

3ait time of each process is folloing

#rocess ait 'ime 2 Service 'ime 3 Arrival 'ime

# /80 C /1(850 F

#1 /5810 F (

#( /-8(0 C /1,80 C /(8170 F 1(

#5 /850 C /1781(0 F 11

Average 3ait 'ime: /C(C1(C110 & , F G.=

Multi -ueue Scheduling

• !ultiple 4ueues are maintained for processes.

• >ach 4ueue can have its on scheduling algorithms.

• #riorities are assigned to each 4ueue.

Page 33: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 33/118

The assignment of physical processors to processes allows processors to accomplish

wor#. The pro!lem of determining when processors shold !e assigned and to which

 processes is called processor schedling or /2' schedling.

"hen more than one process is rna!le, the operating system mst decide which one

first. The part of the operating system concerned with this decision is called the

schedler, and algorithm it ses is called the schedling algorithm.

 

7oals of Scheduling %ob?ectives&

$n this section we try to answer following estion8 "hat the schedler try to achieveF

*any o!:ectives mst !e considered in the design of a schedling discipline. $n

 particlar, a schedler shold consider fairness, efficiency, response time, trnarond

time, throghpt, etc., %ome of these goals depends on the system one is sing for

e&ample !atch system, interactive system or real+time system, etc. !t there are also

some goals that are desira!le in all systems.

 

7eneral 7oals

Fairness 

;airness is important nder all circmstances. 3 schedler ma#es sre that each

Page 34: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 34/118

 process gets its fair share of the /2' and no process can sffer indefinite

 postponement. (ote that giving eivalent or eal time is not fair. Thin# of safety

control  and payroll  at a nclear plant.

Policy Enforcement 

The schedler has to ma#e sre that system?s policy is enforced. ;or e&ample, if

the local policy is safety then the safety control processes mst !e a!le to rn

whenever they want to, even if it means delay in payroll processes.

Efficiency 

%chedler shold #eep the system 4or in particlar /2'5 !sy cent percent of the

time when possi!le. $f the /2' and all the $npt-tpt devices can !e #ept rnning

all the time, more wor# gets done per second than if some components are idle.

Response Time 3 schedler shold minimie the response time for interactive ser.

Turnaround

  3 schedler shold minimie the time !atch sers mst wait for an otpt.

Throughput

  3 schedler shold ma&imie the nm!er of :o!s processed per nit time.

3 little thoght will show that some of these goals are contradictory. $t can !e shown

that any schedling algorithm that favors some class of :o!s hrts another class of

 :o!s. The amont of /2' time availa!le is finite, after all.

 

$reemptive @s >onpreemptive Scheduling

The %chedling algorithms can !e divided into two categories with respect to how

they deal with cloc# interrpts.

Nonpreemptive Scheduling

3 schedling discipline is nonpreemptive if, once a process has !een given the /2',

the /2' cannot !e ta#en away from that process.

;ollowing are some characteristics of nonpreemptive schedling

Page 35: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 35/118

2. In nonpreemptive system, short ?obs are made to wait bylonger ?obs but the overall treatment of all processes is fair.

;. In nonpreemptive system, response times are more predictablebecause incoming high priority ?obs can not displace waiting

 ?obs.

<. In nonpreemptive scheduling, a schedular executes ?obs in thefollowing two situations.

a. *hen a process switches from running state to thewaiting state.

b. *hen a process terminates.

Preemptive Scheduling

3 schedling discipline is preemptive if, once a process has !een given the /2' can

ta#en away.

The strategy of allowing processes that are logically rna!le to !e temporarily

sspended is called 2reemptive %chedling and it is contrast to the Ern to

completionE method.

 %ince processes freently needs to commnicate with other processes therefore,

there is a need for a well+strctred commnication, withot sing interrpts, among

 processes.

 

ace onditions

$n operating systems, processes that are wor#ing together share some common storage

4main memory, file etc.5 that each process can read and write. "hen two or more

 processes are reading or writing some shared data and the final reslt depends on who

rns precisely when, are called race conditions. /oncrrently e&ecting threads that

share data need to synchronie their operations and processing in order to avoid racecondition on shared data. -nly one Gcstomer’ thread at a time shold !e allowed to

e&amine and pdate the shared varia!le.

<ace conditions are also possi!le in -perating %ystems. $f the ready ee is

implemented as a lin#ed list and if the ready ee is !eing maniplated dring the

handling of an interrpt, then interrpts mst !e disa!led to prevent another interrpt

Page 36: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 36/118

 !efore the first one completes. $f interrpts are not disa!led than the lin#ed list cold

 !ecome corrpt.

ritical Section

How to avoid race conditions?

 

The #ey to preventing tro!le involving shared storage is find some way to prohi!it

more than one process from reading and writing the shared data simltaneosly. That

 part of the program where the shared memory is accessed is called the Critical

Section. To avoid race conditions and flawed reslts, one mst identify codes

in Critical Sections  in each thread. The characteristic properties of the code that formaCritical Section are

• odes that reference one or more variables in a 0read-update-write1 fashion while any of those variables is possibly beingaltered by another thread.

• odes that alter one or more variables that are possibly beingreferenced in 0read-updata-write1 fashion by another thread.

• odes use a data structure while any part of it is possibly beingaltered by another thread.

• odes alter any part of a data structure while it is possibly inuse by another thread. 

Page 37: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 37/118

Here, the important point is that when one process is e&ecting shared modifia!le data

in its critical section, no other process is to !e allowed to e&ecte in its critical section.

Ths, the e&ection of critical sections !y the processes is mtally e&clsive in time.

 

#utual /xclusion

 

3 way of ma#ing sre that if one process is sing a shared modifia!le data, the other

 processes will !e e&clded from doing the same thing.

;ormally, while one process e&ectes the shared varia!le, all other processes desiring

to do so at the same time moment shold !e #ept waitingB when that process has

finished e&ecting the shared varia!le, one of the processes waitingB while that process has finished e&ecting the shared varia!le, one of the processes waiting to do

so shold !e allowed to proceed. $n this fashion, each process e&ecting the shared

data 4varia!les5 e&cldes all others from doing so simltaneosly. This is called

*tal D&clsion.

 (ote that mtal e&clsion needs to !e enforced only when processes access shared

modifia!le data + when processes are performing operations that do not conflict with

one another they shold !e allowed to proceed concrrently.

 

#utual /xclusion onditions

$f we cold arrange matters sch that no two processes were ever in their critical

sections simltaneosly, we cold avoid race conditions. "e need for conditions to

hold to have a good soltion for the critical section pro!lem 4mtal e&clsion5.

• >o two processes may at the same moment inside their critical

sections.

• >o assumptions are made about relative speeds of processesor number of $Bs.

• >o process should outside its critical section should block other

processes.

Page 38: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 38/118

• >o process should wait arbitrary long to enter its critical

section.

 

$roposals for Achieving #utual /xclusion

The mtal e&clsion pro!lem is to devise a pre+protocol 4or entry protocol5 and a

 post+protocol 4or e&ist protocol5 to #eep two or more threads from !eing in their

critical sections at the same time. Tanen!am e&amine proposals for critical+section

 pro!lem or mtal e&clsion pro!lem.

Prolem

"hen one process is pdating shared modifia!le data in its critical section, no other process shold allowed to enter in its critical section.

 

Proposal 1 -Disabling Interrupts (Hardware Solution)

Dach process disa!les all interrpts :st after entering in its critical section and re+

ena!le all interrpts :st !efore leaving critical section. "ith interrpts trned off the

/2' cold not !e switched to other process. Hence, no other process will enter its

critical and mtal e&clsion achieved.

!onclusion

isa!ling interrpts is sometimes a sefl interrpts is sometimes a sefl technie

within the #ernel of an operating system, !t it is not appropriate as a general mtal

e&clsion mechanism for sers process. The reason is that it is nwise to give ser

 process the power to trn off interrpts.

 

Proposal 2 - Loc !ariable (So"tware Solution)

$n this soltion, we consider a single, shared, 4loc#5 varia!le, initially 0. "hen a

 process wants to enter in its critical section, it first test the loc#. $f loc# is 0, the

 process first sets it to 1 and then enters the critical section. $f the loc# is already 1, the

 process :st waits ntil 4loc#5 varia!le !ecomes 0. Ths, a 0 means that no process in

Page 39: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 39/118

its critical section, and 1 means hold yor horses + some process is in its critical

section.

!onclusion

The flaw in this proposal can !e !est e&plained !y e&ample. %ppose process 3 sees

that the loc# is 0. =efore it can set the loc# to 1 another process = is schedled, rns,

and sets the loc# to 1. "hen the process 3 rns again, it will also set the loc# to 1, and

two processes will !e in their critical section simltaneosly.

 

Proposal # - Strict $lteration

$n this proposed soltion, the integer varia!le ?trn? #eeps trac# of whose trn is to

enter the critical section. $nitially, process 3 inspect trn, finds it to !e 0, and enters in

its critical section. 2rocess = also finds it to !e 0 and sits in a loop continally testing

?trn? to see when it !ecomes 1./ontinosly testing a varia!le waiting for some vale

to appear is called the Busy-Waiting .

!onclusion

Ta#ing trns is not a good idea when one of the processes is mch slower than the

other. %ppose process 0 finishes its critical section ic#ly, so !oth processes are

now in their noncritical section. This sitation violates a!ove mentioned condition .

%sing S&ste's calls sleep and waeup=asically, what a!ove mentioned soltion do is this8 when a processes wants to enter

in its critical section , it chec#s to see if then entry is allowed. $f it is not, the process

goes into tight loop and waits 4i.e., start !sy waiting5 ntil it is allowed to enter. This

approach waste /2'+time.

 (ow loo# at some interprocess commnication primitives is the pair of steep+wa#ep.

• Sleep

o It is a system call that causes the caller to block, that is,

be suspended until some other process wakes it up.

• *akeup

o It is a system call that wakes up the process.

Page 40: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 40/118

 

Coth 6sleep6 and 6wakeup6 system calls have one parameter that

represents a memory address used to match up 6sleeps6 and

6wakeups6 .

 

 !he Counded Cuer $roducers and onsumers

The !onded !ffer prodcers and consmers assmes that there is a fi&ed !ffer sie

i.e., a finite nm!ers of slots are availa!le.

Statement

To sspend the prodcers when the !ffer is fll, to sspend the consmers when the

 !ffer is empty, and to ma#e sre that only one process at a time maniplates a !ffer

so there are no race conditions or lost pdates.

3s an e&ample how sleep+wa#ep system calls are sed, consider the prodcer+

consmer pro!lem also #nown as !onded !ffer pro!lem.

Two processes share a common, fi&ed+sie 4!onded5 !ffer. The prodcer pts

information into the !ffer and the consmer ta#es information ot.

Tro!le arises when

2. !he producer wants to put a new data in the buer, but bueris already full.SolutionD $roducer goes to sleep and to be awakened when theconsumer has removed data.

;. !he consumer wants to remove data the buer but buer isalready empty.SolutionD onsumer goes to sleep until the producer puts somedata in buer and wakes consumer up.

!onclusionThis approaches also leads to same race conditions we have seen in earlier

approaches. <ace condition can occr de to the fact that access to ?cont? is

nconstrained. The essence of the pro!lem is that a wa#ep call, sent to a process that

is not sleeping, is lost.

Page 41: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 41/118

 

Semaph!res

 

D.". i:#stra 4196>5 a!stracted the #ey notion of mtal e&clsion in his concepts of

semaphores.

"efinition

3 semaphore is a protected varia!le whose vale can !e accessed and altered only !y the

operations 2 and and initialiation operation called ?%emaphoiinitislie?.

=inary %emaphores can assme only the vale 0 or the vale 1 conting semaphores also called

general semaphores can assme only nonnegative vales.

 

The 2 4or wait or sleep or down5 operation on semaphores %, written as 24%5 or wait 4%5, operates

as follows8

P#S$8 %F  % I 0

  THEN  % 8J % + 1

  E&SE  4wait on %5

 

The  4or signal or wa#ep or p5 operation on semaphore %, written as 4%5 or signal 4%5,

operates as follows8

'#S$8 %F  4one or more process are waiting on %5

  THEN 4let one of these processes proceed5

  E&SE  % 8J % K1

 

-perations 2 and are done as single, indivisi!le, atomic action. $t is garanteed that once a

semaphore operations has stared, no other process can access the semaphore ntil operation has

completed. *tal e&clsion on the semaphore, %, is enforced within P#S$ and '#S$.

$f several processes attempt a 24%5 simltaneosly, only process will !e allowed to proceed. The

other processes will !e #ept waiting, !t the implementation of 2 and garantees that processes

will not sffer indefinite postponement.

Page 42: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 42/118

%emaphores solve the lost+wa#ep pro!lem.

$roducer-onsumer $roblem Bsing Semaphores

The %oltion to prodcer+consmer pro!lem ses three semaphores, namely, fll, empty and

mte&.

The semaphore ?fll? is sed for conting the nm!er of slots in the !ffer that are fll. The

?empty? for conting the nm!er of slots that are empty and semaphore ?mte&? to ma#e sre that

the prodcer and consmer do not access modifia!le shared section of the !ffer simltaneosly.

Initialiation

• Set full buer slots to 5.  i.e., semaphore (ull E 5.

• Set empty buer slots to >.

  i.e., semaphore empty E >.

• (or control access to critical section set mutex to 2.  i.e., semaphore mutex E 2.

2rodcer 4 5

"H$@D 4tre5

 prodce+$tem 4 5B

  2 4empty5B

  2 4mte&5B

  enter+$tem 4 5

  4mte&5

  4fll5B

/onsmer 4 5

"H$@D 4tre5

2 4fll5

  2 4mte&5B

  remove+$tem 4 5B

  4mte&5B

  4empty5B

  consme+$tem 4$tem5 

"E("&)!* 

Page 43: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 43/118

3 set of process is in a deadloc# state if each process in the set is waiting for an event

that can !e cased !y only another process in the set. $n other words, each mem!er of 

the set of deadloc# processes is waiting for a resorce that can !e released only !y a

deadloc# process. (one of the processes can rn, none of them can release any

resorces, and none of them can !e awa#ened. $t is important to note that the nm!er of processes and the nm!er and #ind of resorces possessed and reested are

nimportant.

The resorces may !e either physical or logical. D&amples of physical resorces are

2rinters, Tape rivers, *emory %pace, and CPU  /ycles. D&amples of logical

resorces are ;iles, %emaphores, and *onitors.

The simplest e&ample of deadloc# is where process 1 has !een allocated

non+sharea!le resorces A, say, a tap drive, and process has !e

allocated non+shara!le resorce B, say, a printer. (ow, if it trns ot that

 process 1 needs resorce B 4printer5 to proceed and process needs

resorce A 4the tape drive5 to proceed and these are the only two

 processes in the system, each is !loc#ed the other and all sefl wor# in

the system stops. This sitation ifs termed deadloc#. The system is in

deadloc# state !ecase each process holds a resorce !eing reested !y

the other process neither process is willing to release the resorce it

holds.

 

$reemptable and >onpreemptable esources

<esorces come in two flavors8 preempta!le and nonpreempta!le. 3 preempta!le

resorce is one that can !e ta#en away from the process with no ill effects. *emory is

an e&ample of a preempta!le resorce. -n the other hand, a nonpreempta!le resorce

is one that cannot !e ta#en away from process 4withot casing ill effect5. ;or 

e&ample, CD resorces are not preempta!le at an ar!itrary moment.<eallocating resorces can resolve deadloc#s that involve preempta!le resorces.

eadloc#s that involve nonpreempta!le resorces are difficlt to deal with.

Page 44: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 44/118

"!ur %,' c!n#iti!ns that must hold simultaneously for there to be a deadlock.

-. &utual */clusi!n C!n#iti!n

 !he resources involved are non-shareable.

*/planati!n: At least one resource %thread& must be held in a non-shareable mode,that is, only one process at a time claims exclusive control of the resource. If

another process re=uests that resource, the re=uesting process must be delayed

until the resource has been released.

0. 1!l# an# Wait C!n#iti!n

e=uesting process hold already, resources while waiting for re=uested

resources.

*/planati!n: !here must exist a process that is holding a resource already

allocated to it while waiting for additional resource that are currently being held by

other processes.

2. N!3(reemptie C!n#iti!n

esources already allocated to a process cannot be preempted.

*/planati!n: esources cannot be removed from the processes are used to

completion or released voluntarily by the process holding it.

 

,. Circular Wait C!n#iti!n

 !he processes in the system form a circular list or chain where each processin the list is waiting for a resource held by the next process in the list.

/onsider each section of the street as a resorce.

2. #utual exclusion condition applies, since only one vehicle can be on a sectionof the street at a time.

;. Fold-and-wait condition applies, since each vehicle is occupying a section ofthe street, and waiting to move on to the next section of the street.

<. >o-preemptive condition applies, since a section of the street that is a section

of the street that is occupied by a vehicle cannot be taken away from it.

4. ircular wait condition applies, since each vehicle is waiting on the nextvehicle to move. !hat is, each vehicle in the tra+c is waiting for a section ofstreet held by the next vehicle in the tra+c.

The simple rle to avoid traffic deadloc# is that a vehicle shold only enter an intersection if it is

assred that it will not have to stop inside the intersection.

Page 45: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 45/118

$t is not possi!le to have a deadloc# involving only one single process. The deadloc# involves a

circlar “hold+and+wait” condition !etween two or more processes, so “one” process cannot hold

a resorce, yet !e waiting for another resorce that it is holding. $n addition, deadloc# is not

 possi!le !etween two threads in a process, !ecase it is the process that holds resorces, not the

thread that is, each thread has access to the resorces held !y the process.

 

$n general, there are for strategies of dealing with deadloc# pro!lem8

1. The )strich (pproach

Lst ignore the deadloc# pro!lem altogether.

. "eadloc+ "etection and Recovery

etect deadloc# and, when it occrs, ta#e steps to recover.

. "eadloc+ (voidance

3void deadloc# !y carefl resorce schedling.M. "eadloc+ Prevention

2revent deadloc# !y resorce schedling so as to negate at least one of the for

conditions.

eadlock $revention

Havender in his pioneering wor# showed that since all for of the conditions are

necessary for deadloc# to occr, it follows that deadloc# might !e prevented !ydenying any one of the conditions.

 

• *liminati!n !" 4&utual */clusi!n5 C!n#iti!n !he mutual exclusion condition must hold for non-sharableresources. !hat is, several processes cannot simultaneouslyshare a single resource. !his condition is di+cult to eliminatebecause some resources, such as the tap drive and printer, areinherently non-shareable. >ote that shareable resources likeread-only-)le do not re=uire mutually exclusive access andthus cannot be involved in deadlock.

 

Page 46: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 46/118

• *liminati!n !" 41!l# an# Wait5 C!n#iti!n !here are two possibilities for elimination of the secondcondition. !he )rst alternative is that a process re=uest begranted all of the resources it needs at once, prior toexecution. !he second alternative is to disallow a process fromre=uesting resources whenever it has previously allocatedresources. !his strategy re=uires that all of the resources aprocess will need must be re=uested at once. !he system mustgrant resources on 0all or none1 basis. If the complete set ofresources needed by a process is not currently available, thenthe process must wait until the complete set is available. *hilethe process waits, however, it may not hold any resources.

 !hus the 0wait for1 condition is denied and deadlocks simplycannot occur. !his strategy can lead to serious waste of

resources. (or example, a program re=uiring ten tap drivesmust re=uest and receive all ten derives before it beginsexecuting. If the program needs only one tap drive to beginexecution and then does not need the remaining tap drives forseveral hours. !hen substantial computer resources %3 tapedrives& will sit idle for several hours. !his strategy can causeinde)nite postponement %starvation&. Since not all the re=uiredresources may become available at once.

 

• *liminati!n !" 4N!3preempti!n5 C!n#iti!n !he nonpreemption condition can be alleviated by forcing aprocess waiting for a resource that cannot immediately beallocated to relin=uish all of its currently held resources, so thatother processes may use them to )nish. Suppose a systemdoes allow processes to hold resources while re=uestingadditional resources. onsider what happens when a re=uestcannot be satis)ed. A process holds resources a secondprocess may need in order to proceed while second processmay hold the resources needed by the )rst process. !his is adeadlock. !his strategy re=uire that when a process that isholding some resources is denied a re=uest for additionalresources. !he process must release its held resources and, ifnecessary, re=uest them again together with additionalresources. Implementation of this strategy denies the 0no-preemptive1 condition eectively.

Page 47: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 47/118

1igh C!st  *hen a process release resources the processmay lose all its work to that point. One serious conse=uence ofthis strategy is the possibility of inde)nite postponement%starvation&. A process might be held o inde)nitely as itrepeatedly re=uests and releases the same resources.

 

• *liminati!n !" 4Circular Wait5 C!n#iti!n !he last condition, the circular wait, can be denied by imposinga total ordering on all of the resource types and than forcing,all processes to re=uest the resources in order %increasing ordecreasing&. !his strategy impose a total ordering of allresources types, and to re=uire that each process re=uests

resources in a numerical order %increasing or decreasing& ofenumeration. *ith this rule, the resource allocation graph cannever have a cycle.(or example, provide a global numbering of all the resources,as shown

2 Gard

reader

; G $rinter

< G $lotter

4 G !ape drive

8 Gard

punch

 (ow the rle is this8 processes can reest resorces whenever they want to,

 !t all reests mst !e made in nmerical order. 3 process may reest first

 printer and then a tape drive 4order8 , M5, !t it may not reest first a plotter

and then a printer 4order8 , 5. The pro!lem with this strategy is that it may !e

impossi!le to find an ordering that satisfies everyone.

 

eadlock Avoidance

Page 48: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 48/118

This approach to the deadloc# pro!lem anticipates deadloc# !efore it actally occrs. This

approach employs an algorithm to access the possi!ility that deadloc# cold occr and acting

accordingly. This method differs from deadloc# prevention, which garantees that deadloc#

cannot occr !y denying one of the necessary conditions of deadloc#.

$f the necessary conditions for a deadloc# are in place, it is still possi!le to avoid deadloc# !y !eing carefl when resorces are allocated. 2erhaps the most famos deadloc# avoidance

algorithm, de to i:#stra N196>O, is the =an#er’s algorithm. %o named !ecase the process is

analogos to that sed !y a !an#er in deciding if a loan can !e safely made.

 

CankerHs Algorithm

$n this analogy

ustomers

G processes

Bnits Gresources, say,

tape drive

Canker GOperating

System

Cust!m

ersUse# &a/

 $

*

+

D

5

5

5

5

9

8

4

Available

Bnits E 25

 

(ig. 2

$n the a!ove figre, we see for cstomers each of whom has !een granted a nm!er of credit

nits. The !an#er reserved only 10 nits rather than nits to service them. 3t certain moment,the sitation !ecomes

Cust!m

ersUse# &a/

 $

*

+

2

2

;

9

8

4

Available

Bnits E ;

Page 49: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 49/118

D 4

 

(ig. ;

Safe State  The #ey to a state !eing safe is that there is at least one way for all sers to finish. $n

other analogy, the state of figre is safe !ecase with nits left, the !an#er can delay any

reest e&ceptC's, ths letting C  finish and release all for resorces. "ith for nits in hand, the

 !an#er can let either D or B have the necessary nits and so on.

,nsafe State  /onsider what wold happen if a reest from = for one more nit were granted

in a!ove figre .

"e wold have following sitation

Cust!mers

Use# &a/

 $

*

+

D

2

;

;

4

9

8

4

Available

Bnits E 2

 

(ig. <

This is an nsafe state.

$f all the cstomers namely A, B, C, and D as#ed for their ma&imm loans, then !an#er cold not

satisfy any of them and we wold have a deadloc#.

%mportant Note-  $t is important to note that an nsafe state does not imply the e&istence or

even the evental e&istence a deadloc#. "hat an nsafe state does imply is simply that some

nfortnate seence of events might lead to a deadloc#.

The =an#er?s algorithm is ths to consider each reest as it occrs, and see if granting it leads to

a safe state. $f it does, the reest is granted, otherwise, it postponed ntil later. Ha!erman N1969O

has shown that e&ecting of the algorithm has comple&ity proportional to  N  where N  is the

nm!er of processes and since the algorithm is e&ected each time a resorce reest occrs, the

overhead is significant.

 

Page 50: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 50/118

eadlock etection

 

eadloc# detection is the process of actally determining that a deadloc# e&ists andidentifying the processes and resorces involved in the deadloc#.

The !asic idea is to chec# allocation against resorce availa!ility for all possi!le

allocation seences to determine if the system is in deadloc#ed state a. -f corse, the

deadloc# detection algorithm is only half of this strategy. -nce a deadloc# is detected,

there needs to !e a way to recover several alternatives e&ists8

•  !emporarily prevent resources from deadlocked processes.

•Cack o a process to some check point allowing preemption ofa needed resource and restarting the process at the checkpointlater.

• Successively kill processes until the system is deadlock free.

These methods are e&pensive in the sense that each iteration calls the detection

algorithm ntil the system proves to !e deadloc# free. The comple&ity of algorithm

is !4 N 5 where N  is the nm!er of proceeds. 3nother potential pro!lem is starvationB

same process #illed repeatedly.

.E.)R/ .(N(0E.ENT

!emory management is the functionality of an operating system hich

handles or manages primary memory. !emory management keeps track of 

each and every memory location either it is allocated to some process or it

is free. It checks ho much memory is to be allocated to processes. It

decides hich process ill get memory at hat time. It tracks henever

some memory gets freed or unallocated and correspondingly it updates the

status.

Page 51: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 51/118

!emory management provides protection by using to registers% a base

register and a limit register. 'he base register holds the smallest legal

physical memory address and the limit register specifies the siHe of the

range. +or example% if the base register holds 5 and the limit register

is 1(% then the program can legally access all addresses from 5

through ,11.

Instructions and data to memory addresses can be done in folloing ays

• Compile time  88 3hen it is knon at compile time here the process ill

reside% compile time binding is used to generate the absolute code.

• Load time 88 3hen it is not knon at compile time here the process ill reside

in memory% then the compiler generates re8locatable code.

• 5ecution time 88 If the process can be moved during its execution from one

memory segment to another% then binding must be delayed to be done at run

time

Page 52: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 52/118

Dynamic Loading

In dynamic loading% a routine of a program is not loaded until it is called by

the program. All routines are kept on disk in a re8locatable load format. 'he

main program is loaded into memory and is executed. Other routines

methods or modules are loaded on re4uest. <ynamic loading makes better

memory space utiliHation and unused routines are never loaded.

Dynamic Lin)ing

@inking is the process of collecting and combining various modules of code

and data into a executable file that can be loaded into memory and

executed. Operating system can link system level libraries to a program.3hen it combines the libraries at load time% the linking is called static

linking and hen this linking is done at the time of execution% it is called as

dynamic linking.

In static linking% libraries linked at compile time% so program code siHe

becomes bigger hereas in dynamic linking libraries linked at execution

time so program code siHe remains smaller.

Logical versus #hysical Address SpaceAn address generated by the "#$ is a logical address hereas address

actually available on memory unit is a physical address. @ogical address is

also knon a 6irtual address.

6irtual and physical addresses are the same in compile8time and load8time

address8binding schemes. 6irtual and physical addresses differ in execution8

time address8binding scheme.

'he set of all logical addresses generated by a program is referred to as a

logical address space. 'he set of all physical addresses corresponding to

these logical addresses is referred to as a physical address space.

Page 53: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 53/118

'he run8time mapping from virtual to physical address is done by the

memory management unit /!!$0 hich is a hardare device. !!$ uses

folloing mechanism to convert virtual address to physical address.

• 'he value in the base register is added to every address generated by a user

process hich is treated as offset at the time it is sent to memory. +or example%

if the base register value is 1% then an attempt by the user to use address

location 1 ill be dynamically reallocated to location 11.

• 'he user program deals ith virtual addresses; it never sees the real physical

addresses.

S%apping

Sapping is a mechanism in hich a process can be sapped temporarily

out of main memory to a backing store % and then brought back into

memory for continued execution.

2acking store is a usually a hard disk drive or any other secondary storage

hich fast in access and large enough to accommodate copies of all

memory images for all users. It must be capable of providing direct access

to these memory images.

!a?or time consuming part of sapping is transfer time. 'otal transfer time

is directly proportional to the amount of memory sapped. @et us assume

that the user process is of siHe 1D2 and the backing store is a standard

hard disk ith transfer rate of 1 !2 per second. 'he actual transfer of the

1D process to or from memory ill take

1D2 & 1D2 per second

F 1&1 second

F 1 milliseconds

Page 54: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 54/118

Memory Allocation

!ain memory usually has to partitions

Lo% Memory 88 Operating system resides in this memory.

• 6igh Memory 88 $ser processes then held in high memory.

Operating system uses the folloing memory allocation mechanism.

S.N. Memory Allocation Description

1 Single3partition allocation In this type of allocation%

relocation8register schemeis used to protect user

processes from each other%

and from changing

operating8system code and

data. 9elocation register

contains value of smallest

physical address hereas

Page 55: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 55/118

limit register contains range

of logical addresses. >ach

logical address must be less

than the limit register.

( Multiple3partition

allocation

In this type of allocation%

main memory is divided into

a number of fixed8siHed

partitions here each

partition should contain only

one process. 3hen a

partition is free% a process is

selected from the input

4ueue and is loaded into the

free partition. 3hen the

process terminates% thepartition becomes available

for another process.

ragmentation

As processes are loaded and removed from memory% the free memory

space is broken into little pieces. It happens after sometimes that processes

can not be allocated to memory blocks considering their small siHe and

memory blocks remains unused. 'his problem is knon as +ragmentation.

+ragmentation is of to types

S.N. ragmentation Description

1 5ternal

fragmentation

'otal memory space is enough to

satisfy a re4uest or to reside a

process in it% but it is not

contiguous so it can not be used.

( +nternal fragmentation !emory block assigned to

process is bigger. Some portion

of memory is left unused as it

can not be used by another

Page 56: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 56/118

process.

>xternal fragmentation can be reduced by compaction or shuffle memory

contents to place all free memory together in one large block. 'o make

compaction feasible% relocation should be dynamic.

#aging

>xternal fragmentation is avoided by using paging techni4ue. #aging is a

techni4ue in hich physical memory is broken into blocks of the same siHe

called pages /siHe is poer of (% beteen =1( bytes and G1( bytes0. 3hen

a process is to be executed% itEs corresponding pages are loaded into anyavailable memory frames.

@ogical address space of a process can be non8contiguous and a process is

allocated physical memory henever the free memory frame is available.

Operating system keeps track of all free frames. Operating system needs n

free frames to run a program of siHe n pages.

Address generated by "#$ is divided into

• #age num!er 0p1 88 page number is used as an index into a page table hich

contains base address of each page in physical memory.

• #age offset 0d1 88 page offset is combined ith base address to define the

physical memory address.

Page 57: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 57/118

+olloing figure sho the paging table architecture.

Page 58: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 58/118

Segmentation

Segmentation is a techni4ue to break memory into logical pieces here

each piece represents a group of related information. +or example %data

segments or code segment for each process% data segment for operating

system and so on. Segmentation can be implemented using or ithout

using paging.

$nlike paging% segment are having varying siHes and thus eliminates

internal fragmentation. >xternal fragmentation still exists but to lesser

extent.

Address generated by "#$ is divided into

• Segment num!er 0s1 88 segment number is used as an index into a segment

table hich contains base address of each segment in physical memory and a

limit of segment.

• Segment offset 0o1 88 segment offset is first checked against limit and then is

combined ith base address to define the physical memory address.

Page 59: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 59/118

6irtual mem!ry

irtal memory is a technie that allows the e&ection of processes which are not completely

availa!le in memory. The main visi!le advantage of this scheme is that programs can !e larger 

than physical memory. irtal memory is the separation of ser logical memory from physical

memory.

This separation allows an e&tremely large virtal memory to !e provided for programmers when

only a smaller physical memory is availa!le. ;ollowing are the sitations, when entire program

is not reired to !e loaded flly in main memory.

• 'ser written error handling rotines are sed only when an error occred in the data or 

comptation.

• /ertain options and featres of a program may !e sed rarely.

Page 60: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 60/118

• *any ta!les are assigned a fi&ed amont of address space even thogh only a small

amont of the ta!le is actally sed.

• The a!ility to e&ecte a program that is only partially in memory wold conter many

 !enefits.

• @ess nm!er of $- wold !e needed to load or swap each ser program into memory.

• 3 program wold no longer !e constrained !y the amont of physical memory that is

availa!le.

• Dach ser program cold ta#e less physical memory, more programs cold !e rn the

same time, with a corresponding increase in /2' tiliation and throghpt.

irtal memory is commonly implemented !y demand paging. $t can also !e implemented in a

segmentation system. emand segmentation can also !e sed to provide virtal memory.

Page 61: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 61/118

Deman# (aging

3 demand paging system is ite similar to a paging system with swapping. "hen we want to

e&ecte a process, we swap it into memory. <ather than swapping the entire process into

memory, however, we se a lay swapper called pager.

"hen a process is to !e swapped in, the pager gesses which pages will !e sed !efore the

 process is swapped ot again. $nstead of swapping in a whole process, the pager !rings only

those necessary pages into memory. Ths, it avoids reading into memory pages that will not !e

sed in anyway, decreasing the swap time and the amont of physical memory needed.

Hardware spport is reired to distingish !etween those pages that are in memory and those

 pages that are on the dis# sing the valid+invalid !it scheme. "here valid and invalid pages can

 !e chec#ed !y chec#ing the !it. *ar#ing a page will have no effect if the process never attempts

to access the page. "hile the process e&ectes and accesses pages that are memory resident,

e&ection proceeds normally.

Page 62: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 62/118

3ccess to a page mar#ed invalid cases a page1fault trap. This trap is the reslt of the

operating system?s failre to !ring the desired page into memory. =t page falt can !e handled

as following

Step Descripti!n

Step 2 heck an internal table for this process, to

determine whether the reference was a valid or it

was an invalid memory access.

Step ; If the reference was invalid, terminate the process.

If it was valid, but page have not yet brought in,

page in the latter.

Step < (ind a free frame.

Step 4 Schedule a disk operation to read the desired page

into the newly allocated frame.

Page 63: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 63/118

Step 8 *hen the disk read is complete, modify the internal

table kept with the process and the page table to

indicate that the page is now in memory.

Step 9 estart the instruction that was interrupted by theillegal address trap. !he process can now access

the page as though it had always been in memory.

 !herefore, the operating system reads the desired

page into memory and restarts the process as

though the page had always been in memory.

+#antages

;ollowing are the advantages of emand 2aging

• @arge virtal memory.

• *ore efficient se of memory.

• 'nconstrained mltiprogramming. There is no limit on degree of mltiprogramming.

Disa#antages

;ollowing are the disadvantages of emand 2aging

•  (m!er of ta!les and amont of processor overhead for handling page interrpts are

greater than in the case of the simple paged management technies.

• e to the lac# of an e&plicit constraints on a :o!s address space sie.

(age Replacement +lg!rithm

2age replacement algorithms are the technies sing which -perating %ystem decides whichmemory pages to swap ot, write to dis# when a page of memory needs to !e allocated. 2aging

happens whenever a page falt occrs and a free page cannot !e sed for allocation prpose

acconting to reason that pages are not availa!le or the nm!er of free pages is lower than

reired pages.

Page 64: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 64/118

"hen the page that was selected for replacement and was paged ot, is referenced again then it

has to read in from dis#, and this reires for $- completion. This process determines the

ality of the page replacement algorithm8 the lesser the time waiting for page+ins, the !etter is

the algorithm. 3 page replacement algorithm loo#s at the limited information a!ot accessing

the pages provided !y hardware, and tries to select which pages shold !e replaced to minimie

the total nm!er of page misses, while !alancing it with the costs of primary storage and

 processor time of the algorithm itself. There are many different page replacement algorithms.

"e evalate an algorithm !y rnning it on a particlar string of memory reference and

compting the nm!er of page falts.

Re"erence String

The string of memory references is called reference string. <eference strings are generated

artificially or !y tracing a given system and recording the address of each memory reference.

The latter choice prodces a large nm!er of data, where we note two things.

• ;or a given page sie we need to consider only the page nm!er, not the entire address.

• $f we have a reference to a page p, then any immediately following references to page p

will never case a page falt. 2age p will !e in memory after the first referenceB the

immediately following references will not falt.

• ;or e&ample, consider the following seence of addresses + 1,1>,600,1M,A6,96

• $f page sie is 100 then the reference string is 1,,6,1,0,0

7irst In 7irst Out %7I7O' alg!rithm

• -ldest page in main memory is the one which will !e selected for replacement.

• Dasy to implement, #eep a list, replace pages from the tail and add new pages at the

head.

Page 65: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 65/118

Optimal (age alg!rithm

• 3n optimal page+replacement algorithm has the lowest page+falt rate of all algorithms.

3n optimal page+replacement algorithm e&ists, and has !een called -2T or *$(.

• <eplace the page that will not !e sed for the longest period of time . 'se the time when

a page is to !e sed.

Page 66: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 66/118

8east Recently Use# %8RU' alg!rithm

• 2age which has not !een sed for the longest time in main memory is the one which will

 !e selected for replacement.

• Dasy to implement, #eep a list, replace pages !y loo#ing !ac# into time.

(age 9u)ering alg!rithm

• To get process start ic#ly, #eep a pool of free frames.

• -n page falt, select a page to !e replaced.

• "rite new page in the frame of free pool, mar# the page ta!le and restart the process.

•  (ow write the dirty page ot of dis# and place the frame holding replaced page in free

 pool.

8east "reuently Use#%87U' alg!rithm

• 2age with the smallest cont is the one which will !e selected for replacement.

Page 67: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 67/118

• This algorithm sffers from the sitation in which a page is sed heavily dring the

initial phase of a process, !t then is never sed again.

&!st "reuently Use#%&7U' alg!rithm

• This algorithm is !ased on the argment that the page with the smallest cont was

 pro!a!ly :st !roght in and has yet to !e sed.

----------------------------------------------------------------------------------------------------

T1R*+DS

A thread is a flo of execution through the process code% ith its on

program counter% system registers and stack. A thread is also called a light

eight process. 'hreads provide a ay to improve application performance

through parallelism. 'hreads represent a softare approach to improving

performance of operating system by reducing the overhead thread ise4uivalent to a classical process.

>ach thread belongs to exactly one process and no thread can exist outside

a process. >ach thread represents a separate flo of control.'hreads have

been successfully used in implementing netork servers and eb server.

'hey also provide a suitable foundation for parallel execution of applications

on shared memory multiprocessors. +oloing figure shos the orking of 

the single and multithreaded processes.

Page 68: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 68/118

Difference !et%een #rocess and 'hreadS.N. #rocess 'hread

1 #rocess is heavy eight or resource intensive. 'hread is

light

eight

taking

lesser

resources

than a

process.

1 #rocess sitching needs interaction ith

operating system.

'hread

sitching

does not

need tointeract

ith

operating

system.

Page 69: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 69/118

1 In multiple processing environments each

process executes the same code but has its on

memory and file resources.

All

threads

can share

same set

of open

files% childprocesses.

1 If one process is blocked then no other process

can execute until the first process is unblocked.

3hile one

thread is

blocked

and

aiting%

second

thread in

the sametask can

run.

1 !ultiple processes ithout using threads use

more resources.

!ultiple

threaded

processes

use feer

resources.

1 In multiple processes each process operates

independently of the others.

One

thread

can read%

rite or

change

another

threadEs

data.

Advantages of 'hread• 'hread minimiHe context sitching time.

• $se of threads provides concurrency ithin a process.

• >fficient communication.

Page 70: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 70/118

• >conomy8 It is more economical to create and context sitch threads.

• $tiliHation of multiprocessor architectures to a greater scale and efficiency.

'ypes of 'hread'hreads are implemented in folloing to ays

• ,ser Level 'hreads 88 $ser managed threads

• 7ernel Level 'hreads 88 Operating System managed threads acting on kernel%

an operating system core.

,ser Level 'hreadsIn this case% application manages thread management kernel is not aare

of the existence of threads. 'he thread library contains code for creating

and destroying threads% for passing message and data beteen threads% for

scheduling thread execution and for saving and restoring thread contexts.

'he application begins ith a single thread and begins running in that

thread.

Page 71: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 71/118

Advantages

• 'hread sitching does not re4uire Dernel mode privileges.

$ser level thread can run on any operating system.

• Scheduling can be application specific in the user level thread.

• $ser level threads are fast to create and manage.

Disadvantages

• In a typical operating system% most system calls are blocking.

• !ultithreaded application cannot take advantage of multiprocessing.

7ernel Level 'hreads

In this case% thread management done by the Dernel. 'here is no thread

management code in the application area. Dernel threads are supported

directly by the operating system. Any application can be programmed to be

multithreaded. All of the threads ithin an application are supported ithin

a single process.

'he Dernel maintains context information for the process as a hole and for

individuals threads ithin the process. Scheduling by the Dernel is done on

a thread basis. 'he Dernel performs thread creation% scheduling and

management in Dernel space. Dernel threads are generally sloer to create

and manage than the user threads.

Advantages

• Dernel can simultaneously schedule multiple threads from the same process on

multiple processes.

• If one thread in a process is blocked% the Dernel can schedule another thread of 

the same process.

Page 72: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 72/118

• Dernel routines themselves can multithreaded.

Disadvantages

Dernel threads are generally sloer to create and manage than the user threads.

• 'ransfer of control from one thread to another ithin same process re4uires a

mode sitch to the Dernel.

Multithreading Models

Some operating system provide a combined user level thread and Dernel

level thread facility. Solaris is a good example of this combined approach. In

a combined system% multiple threads ithin the same application can run inparallel on multiple processors and a blocking system call need not block

the entire process. !ultithreading models are three types

• !any to many relationship.

• !any to one relationship.

• One to one relationship.

Many to Many Model

In this model% many user level threads multiplexes to the Dernel thread of 

smaller or e4ual numbers. 'he number of Dernel threads may be specific to

either a particular application or a particular machine.

+olloing diagram shos the many to many model. In this model%

developers can create as many user threads as necessary and the

corresponding Dernel threads can run in parallels on a multiprocessor.

Page 73: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 73/118

Many to ne Model

!any to one model maps many user level threads to one Dernel level

thread. 'hread management is done in user space. 3hen thread makes a

blocking system call% the entire process ill be blocked. Only one thread can

access the Dernel at a time%so multiple threads are unable to run in parallel

on multiprocessors.

If the user level thread libraries are implemented in the operating system in

such a ay that system does not support them then Dernel threads use the

many to one relationship modes.

Page 74: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 74/118

ne to ne Model

'here is one to one relationship of user level thread to the kernel level

thread.'his model provides more concurrency than the many to one model.

It also another thread to run hen a thread makes a blocking system call.

It support multiple thread to execute in parallel on microprocessors.

<isadvantage of this model is that creating user thread re4uires the

corresponding Dernel thread. OS&(% indos )' and indos ( use one

to one relationship model.

Difference !et%een ,ser Level & 7ernel

Level 'hreadS.N. ,ser Level 'hreads 7ernel Level

'hread

1 $ser level threads are faster to create andmanage.

Dernel levelthreads are

sloer to

create and

manage.

( Implementation is by a thread library at the Operating

Page 75: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 75/118

user level. system

supports

creation of

Dernel

threads.

5 $ser level thread is generic and can run on

any operating system.

Dernel level

thread is

specific to the

operating

system.

, !ulti8threaded application cannot take

advantage of multiprocessing.

Dernel

routines

themselvescan be

multithreaded.

O(*R+TING S;ST*&3I<O

1+RDW+R*

"omputers operate on many kinds of devices. Jeneral types include storage

devices /disks% tapes0% transmission devices/netork cards% modems0%

and human-interface devices /screen% keyboard% mouse0. Other devices are

more specialiHed. A device communicates ith a computer system by

sending signals over a cable or even through the air.

Page 76: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 76/118

'he device communicates ith the machine via a connection point termed

a port  /for example% a serial port0. If one or more devices use a common

set of ires% the connection is called abus.In other terms% a bus is a set of 

ires and a rigidly defined protocol that specifies a set of messages that can

be sent on the ires.

Daisy chain

3hen device A has a cable that plugs into device 2% and device 2 has a

cable that plugs into device "% and device " plugs into a port on the

computer% this arrangement is called a daisy chain. It usually operates as a

bus.

Controller

A controller is a collection of electronics that can operate a port% a bus% or a

device. A serial8port controller is an example of a simple device controller.

'his is a single chip in the computer that controls the signals on the ires of 

a serial port.

'he S"SI bus controller is often implemented as a separate circuit board /a

host adapter0 that plugs into the computer. It contains a processor%microcode% and some private memory to enable it to process the S"SI

protocol messages. Some devices have their on built8in controllers.

+/ port

An I&O port typically consists of four registers% called

the status% control% data3in% and data3out registers.

S.N. $egister & Description

1 Status $egister

'he status register contains bits that can be read by the

host. 'hese bits indicate states such as hether the current

command has completed% hether a byte is available to be

Page 77: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 77/118

read from the data8in register% and hether there has been a

device error.

( Control register

'he control register can be ritten by the host to start acommand or to change the mode of a device. +or instance% a

certain bit in the control register of a serial port chooses

beteen full8duplex and half8duplex communication% another

enables parity checking% a third bit sets the ord length to 7

or G bits% and other bits select one of the speeds supported

by the serial port.

5 Data3in register

'he data8in register is read by the host to get input.

, Data3out register

'he data out register is ritten by the host to send output.

#olling

#olling is a process by hich a host aits for controller response.It is a

looping process% reading the status register over and over until the busy bit

of status register becomes clear. 'he controller uses&sets the busy bit hen

it is busy orking on a command% and clears the busy bit hen it is ready

to accept the next command. 'he host signals its ish via the command8

ready bit in the command register. 'he host sets the command8ready bit

hen a command is available for the controller to execute.

In the folloing example% the host rites output through a port%

coordinating ith the controller by handshaking

• 'he host repeatedly reads the busy bit until that bit becomes clear.

• 'he host sets the rite bit in the command register and rites a byte into the

data8out register.

• 'he host sets the command8ready bit.

Page 78: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 78/118

• 3hen the controller notices that the command8ready bit is set% it sets the busy

bit.

• 'he controller reads the command register and sees the rite command.

• It reads the data8out register to get the byte% and does the I&O to the device.

• 'he controller clears the command8ready bit% clears the error bit in the status

register to indicate that the device I&O succeeded% and clears the busy bit to

indicate that it is finished.

+/ devices

I&O <evices can be categoriHed into folloing category.

S.N. Category & Description

1 6uman reada!le

Kuman 9eadable devices are suitable for communicating ith

the computer user. >xamples are printers% video display

terminals% keyboard etc.

( Machine reada!le!achine 9eadable devices are suitable for communicating

ith electronic e4uipment. >xamples are disk and tape

drives% sensors% controllers and actuators.

( Communication

"ommunication devices are suitable for communicating ith

remote devices. >xamples are digital line drivers and

modems.

+olloing are the differences beteen I&O <evices

S.N. Criteria & Description

Page 79: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 79/118

1 Data rate

'here may be differences of several orders of magnitude

beteen the data transfer rates.

( Application<ifferent devices have different use in the system.

5 Compleity of Control

A disk is much more complex hereas printer re4uires simple

control interface.

, ,nit of transfer

<ata may be transferred as a stream of bytes or characters

or in larger blocks.

= Data representation

<ifferent data encoding schemes are used for different

devices.

- 5rror Conditions

'he nature of errors differs idely from one device to

another.

Direct Memory Access 0DMA1

!any computers avoid burdening the main "#$ ith programmed I&O by

offloading some of this ork to a special purpose processor. 'his type of 

processor is called% a <irect !emory Access/<!A0 controller. A special

control unit is used to transfer block of data directly beteen an external

device and the main memory% ithout intervention by the processor. 'his

approach is called <irect !emory Access/<!A0.

<!A can be used ith either polling or interrupt softare. <!A is

particularly useful on devices like disks% here many bytes of information

can be transferred in single I&O operations. 3hen used ith an interrupt%

the "#$ is notified only after the entire block of data has been transferred.

Page 80: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 80/118

+or each byte or ord transferred% it must provide the memory address and

all the bus signals controlling the data transfer. Interaction ith a device

controller is managed through a device driver.

Kandshaking is a process beteen the <!A controller and the devicecontroller. It is performed via ires using terms <!A re4uest and <!A

acknoledge.

Step Description

1 <evice driver is instructed to transfer disk data to a buffer

address L.

( <evice driver then instruct disk controller to transfer data to

buffer.

Page 81: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 81/118

5 <isk controller starts <!A transfer.

, <isk controller sends each byte to <!A controller.

= <!A controller transfers bytes to buffer% increases the

memory address% decreases the counter " until " becomes

Hero.

- 3hen " becomes Hero% <!A interrupts "#$ to signal transfer

completion.

Device Controllers

A computer system contains a many types of I&O devices and their

respective controllers

• netork card

• graphics adapter

• disk controller

• <6<89O! controller

• serial port

• $S2

• sound card

O(*R+TING S;ST*& I<O SO7TW+R*S

Page 82: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 82/118

+nterrupts

'he "#$ hardare uses an interrupt re4uest line ire hich helps "#$ to

sense after executing every instruction. 3hen the "#$ checks that a

controller has put a signal on the interrupt re4uest line% the "#$ saves a

state% such as the current value of the instruction pointer% and ?umps to the

interrupt handler routine at a fixed address. 'he interrupt handler part

determines the cause of the interrupt% performs the necessary processing

and executes a interrupt instruction to return the "#$ to its execution state.

'he basic mechanism of interrurpt enables the "#$ to respond to an

asynchronous event% such as hen a device controller become ready for

service. !ost "#$s have to interrupt re4uest lines.

• non3mas)a!le interrupt 8 Such kind of interrupts are reserved for events like

unrecoverable memory errors.

• mas)a!le interrupt 8 Such interrupts can be sitched off by the "#$ before

the execution of critical instructions that must not be interrupted.

'he interrupt mechanism accepts an address 8 a number that selects a

specific interrupt handling routine&function from a small set.In most

architectures% this address is an offset stored in a table called the interrupt

vector table. 'his vector contains the memory addresses of specialiHed

interrupt handlers.

Application +/ +nterface

Application I&O Interface represents the structuring techni4ues and

interfaces for the operating system to enable I&O devices to be treated in a

standard% uniform ay. 'he actual differences lies kernel level modulescalled device drivers hich are custom tailored to corresponding devices but

sho one of the standard interfaces to applications. 'he purpose of the

device8driver layer is to hide the differences among device controllers from

the I&O subsystem of the kernel% such as the I&O system calls. +olloing are

the characteristics of I&O interfaces ith respected to devices.

Page 83: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 83/118

• Character3stream / !loc) 8 A character8stream device transfers bytes in one

by one fashion% hereas a block device transfers a complete unit of bytes.

• Se8uential / random3access 8 A se4uential device transfers data in a fixed

order determined by the device% random8access device can be instructed to seek

position to any of the available data storage locations.

• Synchronous / asynchronous 8 A synchronous device performs data transfers

ith knon response time here as an asynchronous device shos irregular or

unpredictable response time.

• Shara!le / dedicated 8 A sharable device can be used concurrently by several

processes or threads but a dedicated device cannot be used.

• Speed of operation 8 <evice speeds may range from a fe bytes per second to

a fe gigabytes per second.

• $ead3%rite* read only* or %rite only 8 Some devices perform both input and

output% but others support only one data direction that is read only.

Cloc)s

"locks are also called timers. 'he clock softare takes the form of a devicedriver though a clock is neither a blocking device nor a character based

device. 'he clock softare is the clock driver. 'he exact function of the clock

driver may vary depending on operating system. Jenerally% the functions of 

the clock driver include the folloing.

S.N. 'as) Description

1 !aintaining the time of the day 'he clock

driver

implements

the time of

day or the

real time

clock

function.It

Page 84: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 84/118

re4uires

incrementing

a counter at

each clock

tick.

( #reventing processes from running too long As a process

is started%

the

scheduler

initialiHes

the 4uantum

counter in

clock ticks

for the

process. 'heclock driver

decrements

the 4uantum

counter by

1% at every

clock

interrupt.

3hen the

counter gets

to Hero %

clock drivercalls the

scheduler to

set up

another

process.

'hus clock

driver helps

in

preventing

processes

from runninglonger than

time slice

alloed.

5 Accounting for "#$ usage Another

function

Page 85: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 85/118

performed

by clock

driver is

doing "#$

accounting.

"#$accounting

implies

telling ho

long the

process has

run.

, #roviding atchdog timers for parts of the

system itself 

3atchdog

timers are

the timersset by

certain parts

of the

system. +or

example% to

use a floppy

disk% the

system must

turn on the

motor and

then aitabout

=msec for

it to comes

up to speed.

7ernel +/ Su!system

Dernel I&O Subsystem is responsible to provide many services related to

I&O. +olloing are some of the services provided.

• Scheduling 8 Dernel schedules a set of I&O re4uests to determine a good order

in hich to execute them. 3hen an application issues a blocking I&O system call%

the re4uest is placed on the 4ueue for that device. 'he Dernel I&O scheduler

Page 86: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 86/118

rearranges the order of the 4ueue to improve the overall system efficiency and

the average response time experienced by the applications.

• (uffering 8 Dernel I&O Subsystem maintains a memory area knon as buffer

that stores data hile they are transferred beteen to devices or beteen a

device ith an application operation. 2uffering is done to cope ith a speed

mismatch beteen the producer and consumer of a data stream or to adapt

beteen devices that have different data transfer siHes.

• Caching 8 Dernel maintains cache memory hich is region of fast memory that

holds copies of data. Access to the cached copy is more efficient than access to

the original.

• Spooling and Device $eservation A spool is a buffer that holds output for a

device% such as a printer% that cannot accept interleaved data streams. 'he

spooling system copies the 4ueued spool files to the printer one at a time. In

some operating systems% spooling is managed by a system daemon process. In

other operating systems% it is handled by an in kernel thread.

• 5rror 6andling An operating system that uses protected memory can guard

against many kinds of hardare and application errors.

Device driver

<evice driver is a program or routine developed for an I&O device. A device

driver implements I&O operations or behaviours on a specific class of 

devices. +or example a system supports one or a number of multiple brands

of terminals% all slightly different terminals may have a single terminal

driver. In the layered structure of I&O system% device driver lies beteen

interrupt handler and device independent I&O softare. 'he ?ob of a device

driver are folloing.

• 'o accept re4uest from the device independent softare above it.

• 'o see to it that the re4uest is executed.

Page 87: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 87/118

Ko a device driver handles a re4uest is as follos: Suppose a re4uest

comes to read a block ). If the driver is idle at the time a re4uest arrives% it

starts carrying out the re4uest immediately. Otherise% if the driver is

already busy ith some other re4uest% it places the ne re4uest in the

4ueue of pending re4uests

7ile systems

3 file is a named collection of related information that is recorded on secondary storage sch as

magnetic dis#s, magnetic tapes and optical dis#s.$n general, a file is a seence of !its, !ytes,

lines or records whose meaning is defined !y the files creator and ser.

7ile Structure

;ile strctre is a strctre, which is according to a reired format that operating system can

nderstand.

• 3 file has a certain defined strctre according to its type.

• 3 te&t file is a seence of characters organied into lines.

• 3 sorce file is a seence of procedres and fnctions.

• 3n o!:ect file is a seence of !ytes organied into !loc#s that are nderstanda!le !y the

machine.

• "hen operating system defines different file strctres, it also contains the code to

spport these file strctre. 'ni&, *%+-% spport minimm nm!er of file strctre.

Page 88: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 88/118

7ile Type

;ile type refers to the a!ility of the operating system to distingish different types of file sch as

te&t files sorce files and !inary files etc. *any operating systems spport many types of files.

-perating system li#e *%+-% and '($) have the following types of files8

Or#inary =les

• These are the files that contain ser information.

• These may have te&t, data!ases or e&ecta!le program.

• The ser can apply varios operations on sch files li#e add, modify, delete or even

remove the entire file.

Direct!ry =les

• These files contain list of file names and other information related to these files.

Special =les:

• These files are also #nown as device files.

• These files represent physical device li#e dis#s, terminals, printers, networ#s, tape drive

etc.

These files are of two types

• !haracter special files + data is handled character !y character as in case of terminals or 

 printers.

• 2loc+ special files + data is handled in !loc#s as in the case of dis#s and tapes.

7ile +ccess &echanisms

;ile access mechanism refers to the manner in which the records of a file may !e accessed.

There are several ways to access files

Page 89: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 89/118

• %eential access

• irect<andom access

$nde&ed seential access

Seuential access

3 seential access is that in which the records are accessed in some seence i.e the

information in the file is processed in order, one record after the other. This access method is the

most primitive one. D&ample8 /ompilers sally access files in this fashion.

Direct<Ran#!m access

• <andom access file organiation provides, accessing the records directly.

• Dach record has its own address on the file with !y the help of which it can !e directly

accessed for reading or writing.

• The records need not !e in any seence within the file and they need not !e in ad:acent

locations on the storage medim.

In#e/e# seuential access

• This mechanism is !ilt p on !ase of seential access.

• 3n inde& is created for each file which contains pointers to varios !loc#s.

• $nde& is searched seentially and its pointer is sed to access the file directly.

Space +ll!cati!n

;iles are allocated dis# spaces !y operating system. -perating systems deploy following threemain ways to allocate dis# space to files.

• /ontigos 3llocation

• @in#ed 3llocation

Page 90: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 90/118

• $nde&ed 3llocation

C!ntigu!us +ll!cati!n

Dach file occpy a contigos address space on dis#.

• 3ssigned dis# address is in linear order.

• Dasy to implement.

• D&ternal fragmentation is a ma:or isse with this type of allocation technie.

8in>e# +ll!cati!n

• Dach file carries a list of lin#s to dis# !loc#s.

• irectory contains lin# pointer to first !loc# of a file.

•  (o e&ternal fragmentation

• Dffectively sed in seential access file.

• $nefficient in case of direct access file.

In#e/e# +ll!cati!n

• 2rovides soltions to pro!lems of contigos and lin#ed allocation.

• 3 inde& !loc# is created having all pointers to files.

• Dach file has its own inde& !loc# which stores the addresses of dis# space occpied !y

the file.

• irectory contains the addresses of inde& !loc#s of files.

Page 91: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 91/118

PR)TE!T%)N (N" SE!,R%T/

Security refers to providing a protection system to computer system

resources such as "#$% memory% disk% softare programs and most

importantly data&information stored in the computer system. If a computer

program is run by unauthoriHed user then he&she may cause severe

damage to computer or data stored in it. So a computer system must be

protected against unauthoriHed access% malicious access to system memory%

viruses% orms etc. 3eEre going to discuss folloing topics in this article.

• Authentication

• One 'ime passords

• #rogram 'hreats

• System 'hreats

• "omputer Security "lassifications

Authentication

Authentication refers to identifying the each user of the system and

associating the executing programs ith those users. It is the responsibility

of the Operating System to create a protection system hich ensures that a

user ho is running a particular program is authentic. Operating Systems

generally identifies&authenticates users using folloing three ays:

• ,sername / #ass%ord 8 $ser need to enter a registered username and

passord ith Operating system to login into the system.

• ,ser card/)ey 8 $ser need to punch card in card slot% or enter key generated

by key generator in option provided by operating system to login into the

system.

Page 92: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 92/118

• ,ser attri!ute 3 fingerprint/ eye retina pattern/ signature 8 $ser need to

pass his&her attribute via designated input device used by operating system to

login into the system.

ne 'ime pass%ords

One time passords provides additional security along ith normal

authentication. In One8'ime #assord system% a uni4ue passord is

re4uired every time user tries to login into the system. Once a one8time

passord is used then it can not be used again. One time passord are

implemented in various ays.

• $andom num!ers 8 $sers are provided cards having numbers printed along

ith corresponding alphabets. System asks for numbers corresponding to fe

alphabets randomly chosen.

• Secret )ey 8 $ser are provided a hardare device hich can create a secret id

mapped ith user id. System asks for such secret id hich is to be generated

every time prior to login.

• Net%or) pass%ord 8 Some commercial applications send one time passord

to user on registered mobile& email hich is re4uired to be entered prior to

login.

#rogram 'hreats

Operating systemEs processes and kernel do the designated task as

instructed. If a user program made these process do malicious tasks then it

is knon as #rogram 'hreats. One of the common example of program

threat is a program installed in a computer hich can store and send user

credentials via netork to some hacker. +olloing is the list of some ellknon program threats.

• 'ro"an 6orse 8 Such program traps user login credentials and stores them to

send to malicious user ho can later on login to computer and can access

system resources.

Page 93: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 93/118

• 'rap Door 8 If a program hich is designed to ork as re4uired% have a security

hole in its code and perform illegal action ithout knoledge of user then it is

called to have a trap door.

• Logic (om! 8 @ogic bomb is a situation hen a program misbehaves only hen

certain conditions met otherise it orks as a genuine program. It is harder to

detect.

• Virus 8 6irus as name suggest can replicate themselves on computer system

.'hey are highly dangerous and can modify&delete user files% crash systems. A

virus is generatlly a small code embedded in a program. As user accesses the

program% the virus starts getting embedded in other files& programs and can

make system unusable for user.

System 'hreats

System threats refers to misuse of system services and netork

connections to put user in trouble. System threats can be used to launch

program threats on a complete netork called as program attack. System

threats creates such an environment that operating system resources& user

files are mis8used. +olloing is the list of some ell knon system threats.

• orm 83orm is a process hich can choked don a system performance by

using system resources to extreme levels.A 3orm process generates its multiple

copies here each copy uses system resources% prevents all other processes to

get re4uired resources. 3orms processes can even shut don an entire netork.

• #ort Scanning 8 #ort scanning is a mechanism or means by hich a hacker can

detects system vulnerabilities to make an attack on the system.

• Denial of Service 8 <enial of service attacks normally prevents user to make

legitimate use of the system. +or example user may not be able to use internet

if denial of service attacks broserEs content settings.

Page 94: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 94/118

Computer Security Classifications

As per the $.S. <epartment of <efense 'rusted "omputer SystemEs

>valuation "riteria there are four security classifications in computer

systems: A% 2% "% and <. 'his is idely used specifications to determine and

model the security of systems and of security solutions. +olloing is the

brief description of each classfication.

S.N. Classification

'ype

Description

1 'ype A Kighest @evel. $ses formal design

specifications and verification

techni4ues.Jrants a high degree of

assurance of process security.

( 'ype 2 #rovides mandatory protection system.

Kave all the properties of a class "(

system. Attaches a sensitivity label to each

ob?ect.It is of three types.

• (9 8 !aintains the security label of 

each ob?ect in the system.@abel is

used for making decisions to access

control.

• (: 8 >xtends the sensitivity labels

to each system resource% such as

storage ob?ects% supports covert

channels and auditing of events.

• (; 8 Allos creating lists or user

groups for access8control to grant

access or revoke access to a given

named ob?ect.

5 'ype " #rovides protection and user accountability

Page 95: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 95/118

using audit capabilities. It is of to types.

• C9 8 Incorporates controls so that

users can protect their privateinformation and keep other users

from accidentally reading & deleting

their data. $)IL versions are mostly

"l class.

• C: 8 Adds an individual8level access

control to the capabilities of a "l

level system

, 'ype < @oest level. !inimum protection. !S8

<OS% 3indo 5.1 fall in this category.

1. Which of the following is NOT a vali ealock !revention scheme" #$%T& '(

2)))*

(a) Release all resources before requesting a new resource

(b) Number the resources uniquely and never request a lower numbered resource than the

last one requested.

(c) Never request a resource after releasing any resource

(d) Request and all required resources be allocated before execution.

 %nswer+ (c)

34 2. ,et m)/m4 0e mtees #0inar sema!hores* an ) /. 4 0e!rocesses.(!!ose each !rocess i eectes the following+

3. wait (m[i]); wait(m[(i+1) mode 4]);

4.

Page 96: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 96/118

5.   ------

6.

7.   release (m[i]); release (m[(i+1)mod 4]);

54 This col case #$%T& '( 2)))*(a) Thrashing(b) Deadlock 

(c) tarvation! but not deadlock (d) None of the above

 %nswer+ (b)&!lanation+

 "ou can easily see a deadlock in a situation where..#$%& has acquired m$%& and waiting for m$'&#$'& has acquired m$'& and waiting for m$&#$& has acquired m$& and waiting for m$&#$& has acquired m$& and waiting for m$%&

3. % gra!hics car has on 0oar memor of 1 M5. Which of the following moescan the car not s!!ort" #$%T& '( 2)))*(a) '*%% x +%% resolution with ,* colours on a '- inch monitor

(b) '*%% x +%% resolution with '* million colours on a '+ inch monitor(c) %% x +%% resolution with '* million colours on a '- inch monitor(d) %% x %% resolution with ,* colours on a '+ inch monitor

 %nswer+ (b)&!lanation+/onitor si0e doesn1t matter here. o! we can easily deduct that answer should be (b) as thishas the highest memory requirements. 2et us verify it.Number of bits required to store a '*/ colors 3ixel 4 ceil(log('*5'%%%%%%)) 4 +Number of bytes required for '*%% x +%% resolution with '*/ colors 4 ('*%% 5 +%% 5 +)6

 which is '7%%%%%% (greater than '/8).

4 'onsier a virtal memor sstem with 66O !age re!lacement !olic. 6or anar0itrar !age access !attern increasing the nm0er of !age frames in mainmemor will #$%T& '( 2))1*a) 9lways decrease the number of 3age faults

 b) 9lways increase the number of 3age faultsc) ome times increase the number of 3age faultsd) Never affect the number of 3age faults

 %nswer+ (c)&!lanation+:ncrementing the number of 3age frames doesn1t always decrease the 3age faults (8elady1s

 9nomaly

9. Which of the following re:ires a evice river" #$%T& '( 2))1*a) Register

 b) ;ache

c) /ain memory d) Disk

 %nswer+ (d)

;. 'onsier a machine with ;4 M5 !hsical memor an a 32-0it virtal aresss!ace. f the !age si<e is 4=5 what is the a!!roimate si<e of the !age ta0le"#$%T& 2))1*(a) '* /8(b) /8

Page 97: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 97/118

(c) /8(d) + /8

 %nswer+ (c)&!lanation+

 9 3age entry is used to get address of 3hysical memory. <ere we assume that single level of#aging is ha33ening. o the resulting 3age table will contain entries for all the 3ages of the

 =irtual address s3ace.

Number of entries in page table =

(virtual address space size)/(page size)

>sing above formula we can say that there will be ?(@') 4 ?% entries in 3age table.No. of bits required to address the *+/8 #hysical memory 4 *.o there will be ?(*@') 4 ?'+ 3age frames in the 3hysical memory. 9nd 3age table needsto store the address of all these ?'+ 3age frames. Therefore! each 3age table entry willcontain '+ bits address of the 3age frame and ' bit for valid@invalid bit.ince memory is byte addressable. o we take that each 3age table entry is '* bits i.e. byteslong.

Size of page table =

(total number of page table entries) *(size of a page table entry)  = (2^20 *2) = 2!

 'onsier eterson>s algorithm for mtal eclsion 0etween two concrrent!rocesses i an ?. The !rogram eecte 0 !rocess is shown 0elow.

repeat

flag [i] = true;

tur = !;

 w"ile ( # ) do o-op;

$ter %riti%al se%tio& perform a%tios& t"e e'it %riti%al

se%tio

flag [ i ] = false;

#erform ot"er o-%riti%al se%tio a%tios.

util false;

64 6or the !rogram to garantee mtal eclsion the !reicate in the whileloo! shol 0e #$%T& 2))1*a) flag $A& 4 true and turn 4 i

 b) flag $A& 4 true and turn 4 Ac) flag $i& 4 true and turn 4 Ad) flag $i& 4 true and turn 4 i

 %nswer+ (b)

8asically! #eterson1s algorithm 3rovides guaranteed mutual exclusion by using the twofollowing constructs B flag[]  and turn. flag[]  controls that the willingness of a 3rocess to beentered in critical section. Chile turncontrols the 3rocess that is allowed to be entered incritical section. o by re3lacing # with the following!

 flag [j] = true and turn = j3rocess i will not enter critical section if 3rocess A wants to enter critical section and it is3rocess A1s turn to enter critical section. The same conce3t can be extended for more than two3rocesses. or details! refer the following.

Page 98: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 98/118

@+ More than one wor are !t in one cache 0lock to #$%T& 2))1*(a) ex3loit the tem3oral locality of reference in a 3rogram(b) ex3loit the s3atial locality of reference in a 3rogram(c) reduce the miss 3enalty (d) none of the above

 %nswer+ (b)Tem3oral locality refers to the reuse of s3ecific data and6or resources within relatively smalltime durations. 3atial locality refers to the use of data elements within relatively closestorage locations.To ex3loit the s3atial locality! more than one word are 3ut into cache block.

A. Which of the following statements is false" #$%T& 2))1*a) =irtual memory im3lements the translation of a 3rogram1s address s3ace into 3hysicalmemory address s3ace

 b) =irtual memory allows each 3rogram to exceed the si0e of the 3rimary memory c) =irtual memory increases the degree of multi3rogrammingd) =irtual memory reduces the context switching overhead

 %nswer+ (d):n a system with virtual memory context switch includes extra overhead in switching of

address s3aces.

1). 'onsier a set of n tasks with known rntimes r1 r2 / rn to 0e rn on ani!rocessor machine. Which of the following !rocessor scheling algorithms

 will reslt in the maimm throgh!t" #$%T& 2))1*(a) Round@Robin(b) hortest@Eob@irst(c) <ighest@Res3onse@Ratio@Next(d) irst@;ome@irst@erved

 %nswer+ (b)

11. (!!ose the time to service a !age falt is on the average 1) millisecons while a memor access takes 1 microsecon. Then a AA.AAB hit ratio reslts in

average memor access time of #$%T& '( 2)))*(a) '.7777 milliseconds(b) ' millisecond(c) 7.777 microseconds(d) '.7777 microseconds

 %nswer+ (d)&!lanation+

"verage memory access time =

  #($ of page miss)*(time to service a page fault) %

  ($ of page &it)*(memory access time)'/00

784 o! average memory access time in microseconds is.(77.775' F %.%'5'%5'%%%)6'%% 4 (77.77F'%%)6'%%% 4 '77.776'%%% 4'.7777 Gs

12. Which of the following nee not necessaril 0e save on a contet switch 0etween !rocesses" #$%T& '( 2)))*(a) Heneral 3ur3ose registers(b) Translation look@aside buffer(c) #rogram counter(d) 9ll of the above

 %nswer+ (b)&!lanation+

Page 99: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 99/118

:n a 3rocess context switch! the state of the first 3rocess must be saved somehow! so that! when the scheduler gets back to the execution of the first 3rocess! it can restore this state andcontinue.The state of the 3rocess includes all the registers that the 3rocess may be using! es3ecially the3rogram counter! 3lus any other o3erating system s3ecific data that may be necessary.

 9 Translation lookaside buffer (T28) is a ;#> cache that memory management hardwareuses to im3rove virtual address translation s3eed. 9 T28 has a fixed number of slots thatcontain 3age table entries! which ma3 virtual addresses to 3hysical addresses. In a contextswitch! some T28 entries can become invalid! since the virtual@to@3hysical ma33ing isdifferent. The sim3lest strategy to deal with this is to com3letely flush the T28.

13. Where oes the swa! s!ace resie " #$%T& 2))1*(a) R9/(b) Disk (c) RI/(d) In@chi3 cache

 %nswer+ (b)&!lanation+wa3 s3ace is an area on disk that tem3orarily holds a 3rocess memory image. Chen3hysical memory demand is sufficiently low! 3rocess memory images are brought back into

3hysical memory from the swa3 area. <aving sufficient swa3 s3ace enables the system tokee3 some 3hysical memory free at all times.

14. Which of the following oes not interr!t a rnning !rocess" (H9TJ ; %%')(a) 9 device(b) Timer(c) cheduler 3rocess(d) #ower failure

 %nswer+ (c)

&!lanation+cheduler 3rocess doesn1t interru3t any 3rocess! it1s Eob is to select the 3rocesses forfollowing three 3ur3oses.

 Long-term scheduler(or Aob scheduler) Bselects which 3rocesses should be brought into theready queue Short-term scheduler(or ;#> scheduler) Bselects which 3rocess should be executed next andallocates ;#>.

 Mid-term Scheduler (wa33er)@ 3resent in all systems with virtual memory! tem3orarilyremoves 3rocesses from main memory and 3laces them on secondary memory (such as a disk drive) or vice versa. The mid@term scheduler may decide to swa3 out a 3rocess which has not

 been active for some time! or a 3rocess which has a low 3riority! or a 3rocess which is 3agefaulting frequently! or a 3rocess which is taking u3 a large amount of memory in order to freeu3 main memory for other 3rocesses! swa33ing the 3rocess back in later when more memory is available! or when the 3rocess has been unblocked and is no longer waiting for a resource.

19. Which of the following scheling algorithms is non-!reem!tive" #$%T& '(2))2*

a) Round Robin b) irst@:n irst@Iutc) /ultilevel Kueue chedulingd) /ultilevel Kueue cheduling with eedback

 %nswer+ (b)

1;. Csing a larger 0lock si<e in a fie 0lock si<e file sstem leas to #$%T& '(2))3*

Page 100: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 100/118

a) better disk through3ut but 3oorer disk s3ace utili0ation b) better disk through3ut and better disk s3ace utili0ationc) 3oorer disk through3ut but better disk s3ace utili0ationd) 3oorer disk through3ut and 3oorer disk s3ace utili0ation

 9nswer (a):f block si0e is large then seek time is less (fewer blocks to seek) and disk 3erformance isim3roved! but remember larger block si0e also causes waste of disk s3ace.

17. 'onsier the following statements with res!ect to ser-level threas ankernel s!!orte threasi. contet switch is faster with kernel-s!!orte threasii. for ser-level threas a sstem call can 0lock the entire !rocessiii. =ernel s!!orte threas can 0e schele ine!enentl iv. Cser level threas are trans!arent to the kernel

 Which of the a0ove statements are tre" #$%T& '( 2))4*

a) (ii)! (iii) and (iv) only  b) (ii) and (iii) only c) (i) and (iii) only d) (i) and (ii) only 

 9nswer(a)

18. The minimm nm0er of !age frames that mst 0e allocate to a rnning!rocess in a virtal memor environment is etermine 0 #$%T& '( 2))4*a) the instruction set architecture

 b) 3age si0ec) 3hysical memory si0ed) number of 3rocesses in memory 

 9nswer (a)Jach 3rocess needs minimum number of 3ages based on instruction set architecture.Jxam3le :8/ -%L * 3ages to handle /=; (storage to storage move) instruction:nstruction is * bytes! might s3an 3ages. 3ages to handle from.

3ages to handle to.

1A. n a sstem with 32 0it virtal aresses an 1 =5 !age si<e se of one-level!age ta0les for virtal to !hsical aress translation is not !ractical 0ecase of#$%T& '( 2))3*a) the large amount of internal fragmentation

 b) the large amount of external fragmentationc) the large memory overhead in maintaining 3age tablesd) the large com3utation overhead in the translation 3rocess

 9nswer (c)ince 3age si0e is too small it will make si0e of 3age tables huge.

Size of page table =

  (total number of page table entries) *(size of a page table entry)2et us see how many entries are there in 3age table

Number of entries in page table =

  (virtual address space size)/(page size)

  = (2^2)/(2^0)

= 2^22

Now! let us see how big each entry is.:f si0e of 3hysical memory is ,' /8 then number of bits required to address a byte in ,'

Page 101: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 101/118

/8 is 7. o! there will be (,'/8)6('M8) 4 (?7)6(?'%) 3age frames in 3hysical memory.To address a 3age frame '7 bits are required. Therefore! each entry in 3age table is requiredto have '7 bits.

Note t&at page table entry also &olds auiliary information about

t&e page suc&

as a present bit+ a dirty or modified bit+ address space or process,- information+

amongst ot&ers. So size of page table

(total number of page table entries) *(size of a page table

entry)

  (2^22 *) bytes

  .1 !

 9nd this much memory is required for each 3rocess because each 3rocess maintains its own 3agetable. 9lso! si0e of 3age table will be more for 3hysical memory more than ,'/8. Therefore! it isadvised to use multilevel 3age table for such scenarios.

 % !rocess eectes the coe

  for ()3

  for ()3

  for ()3

774 The total nm0er of chil !rocesses create is(9) (8) +(;) -(D)

 9nswer (;)2et us 3ut some label names for the three lines

  for ()3 // 4ine

  for ()3 // 4ine 2

  for ()3 // 4ine

  4 // 5&ere 6ill be c&ild process created by line

  / 7

  42 42 // 5&ere 6ill be 2 c&ild processes created by line 2

 / 7 / 7

4 4 4 4 // 5&ere 6ill be 8 c&ild processes created by line

734 Ce can also use direct formula to get the number of child 3rocesses. Cith n fork statements!there are always ?n B ' child 3rocesses. 9lso see this 3ost for more details.

 consier the 3 !rocesses 1 2 an 3 shown in the ta0le

9rocess "rrival time 5ime unit re:uired

  9 0 1

  92 ;

  9 8

Page 102: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 102/118

794 The com!letion orer of the 3 !rocesses ner the !olicies 6'6( an DD(#ron ro0in scheling with 'C :antm of 2 time nits* are(9) 6'6(L #'! #! # DD2L #'! #! #(8) 6'6(L #'! #! # DD2L #'! #! #(;) 6'6(L #'! #! # DD2L #'! #! #(D) 6'6(L #'! #! # DD2L #'! #! #

 9nswer (;)

22. 'onsier the virtal !age reference string1 2 3 2 4 1 3 2 4 1On a eman !age virtal memor sstem rnning on a com!ter sstem thatmain memor si<e of 3 !ages frames which are initiall em!t. ,et ,DC 66Oan OTM%, enote the nm0er of !age falts ner the corres!oning !agere!lacements !olic. Then(9) I#T:/92 2R> :I(8) I#T:/92 :I 2R>(;) I#T:/92 4 2R>(D) I#T:/92 4 :I

 9nswer (8)The I#T:/92 will be ,! :I * and 2R> 7.

23. % file sstem with 3)) $5te ses a file escri!tor with 8 irect 0lockaress. 1 inirect 0lock aress an 1 o0l inirect 0lock aress. The si<eof each isk 0lock is 128 5tes an the si<e of each isk 0lock aress is 8 5tes.The maimm !ossi0le file si<e in this file sstem is(9) Mbytes(8) , Mbytes(;) % 8ytes(D) De3endent on the si0e of the disk

 9nswer (8)

Total number of 3ossible addresses stored in a disk block 4 '6 4 '*/aximum number of addressable bytes due to direct address block 4 5'/aximum number of addressable bytes due to ' single indirect address block 4 '*5'/aximum number of addressable bytes due to ' double indirect address block 4 '*5'*5'The maximum 3ossible file si0e 4 5' F '*5' F '*5'*5' 4 ,M8

24* % threa is sall efine as a Elight weight !rocess> 0ecase an o!eratingsstem #O(* maintains smaller ata strctres for a threa than for a !rocess.n relation to this which of the followings is TDC&"(9) In 3er@thread basis! the I maintains only ;#> register state(8) The I does not maintain a se3arate stack for each thread(;) In 3er@thread basis! the I does not maintain virtual memory state(D) In 3er thread basis! the I maintains only scheduling and accounting information.

 9nswer (9)Threads are called Olight weight 3rocess1 because they only need storage for stack andregisters. They don1t need se3arate s3ace for other things like code segment! global data! etc

29* ,et the !age falt service time 0e 1)ms in a com!ter with average memoraccess time 0eing 2)ns. f one !age falt is generate for ever 1)F; memoraccesses what is the effective access time for the memor"(9) 'ns(8) %ns

Page 103: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 103/118

(;) ns(D) ,ns

 9nswer (8)

4et 9 be t&e page fault rate

<ffective emory "ccess 5ime = p * (page fault service time) %

( p) * (emory access time)  = ( /(0^>) )* 0 * (0^>) ns %

  ( /(0^>)) * 20 ns

  = 0 ns (appro)

2;* %n a!!lication loas 1)) li0raries at start!. ,oaing each li0rar re:ireseactl one isk access. The seek time of the isk to a ranom location is givenas 1)ms. Dotational s!ee of isk is ;)))r!m. f all 1)) li0raries are loaefrom ranom locations on the isk how long oes it take to loa all li0raries"#The time to transfer ata from the isk 0lock once the hea has 0een!ositione at the start of the 0lock ma 0e neglecte*(9) %.,%s(8) '.,%s(;) '.,s(D) '.%%s

 9nswer (8)ince transfer time can be neglected! the average access time is sum of average seek time andaverage rotational latency. 9verage seek time for a random location time is given as '% ms.The average rotational latency is half of the time needed for com3lete rotation. :t is given that*%%% rotations need ' minute. o one rotation will take *%6*%%% seconds which is '% ms.Therefore average rotational latency is half of '% ms! which is ,ms.

"verage dis access time = see time % rotational latency

= 0 ms % 1 ms= 1 ms

?or 00 libraries+ t&e average dis access time 6ill be 1*00 ms

7:4'onsier the following ta0le of arrival time an 0rst time for three !rocesses) 1 an 2.

9rocess "rrival time !urst 5ime

90 0 ms ms

9 ms 8 ms

92 2 ms ms

7;4 The !re-em!tive shortest ?o0 first scheling algorithm is se. (cheling is

carrie ot onl at arrival or com!letion of !rocesses. What is the average waiting time for the three !rocesses"(9) ,.% ms(8) +. ms(;) *. ms(D) -. ms

 9nswerL B (9)#rocess #% is allocated 3rocessor at % ms as there is no other 3rocess in ready queue. #% is3reem3ted after ' ms as #' arrives at ' ms and burst time for #' is less than remaining time of #%. #' runs for +ms. # arrived at ms but #' continued as burst time of # is longer than

Page 104: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 104/118

#'. 9fter #' com3letes! #% is scheduled again as the remaining time for #% is less than the burst time of #.#% waits for + ms! #' waits for % ms amd # waits for '' ms. o average waiting time is(%F+F'')6 4 ,.

28* ,et the time taken to switch 0etween ser an kernel moes of eection 0et1 while the time taken to switch 0etween two !rocesses 0e t2. Which of thefollowing is TDC&" #$%T& '( 2)11*(9) t' P t(8) t' 4 t(;) t' t(D) Nothing can be said about the relation between t' and t

 9nswerL @ (;)#rocess switching involves mode switch. ;ontext switching can occur only in kernel mode.

2A* % sstem ses 66O !olic for !age re!lacement. t has 4 !age frames withno !ages loae to 0egin with. The sstem first accesses 1)) istinct !ages insome orer an then accesses the same 1)) !ages 0t now in the reverse orer.Gow man !age falts will occr" #$%T& '( 2)1)*

(9) '7*(8) '7(;) '7-(D) '7,

 9nswer (9) 9ccess to '%% 3ages will cause '%% 3age faults. Chen these 3ages are accessed in reverseorder! the first four accesses will node cause 3age fault. 9ll other access to 3ages will cause3age faults. o total number of 3age faults will be '%% F 7*.

3)* Which of the following statements are tre" #$%T& '( 2)1)*. (hortest remaining time first scheling ma case starvation. reem!tive scheling ma case starvation

. Don ro0in is 0etter than 6'6( in terms of res!onse time(9) : only (8) : and ::: only (;) :: and ::: only (D) :! :: and :::

 9nswer (D):) hortest remaining time first scheduling is a 3reem3tive version of shortest Aob scheduling.:t may cause starvation as shorter 3rocesses may kee3 coming and a long ;#> burst 3rocessnever gets ;#>.::) #reem3tion may cause starvation. :f 3riority based scheduling with 3reem3tion is used!then a low 3riority 3rocess may never get ;#>.:::) Round Robin cheduling im3roves res3onse time as all 3rocesses get ;#> after as3ecified time.

31* 'onsier the methos se 0 !rocesses 1 an 2 for accessing theircritical sections whenever neee as given 0elow. The initial vales of share

 0oolean varia0les (1 an (2 are ranoml assigne.

 et"od sed * #1

6&ile (S == S2) 3

@ritica Section

S = S23

Page 105: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 105/118

 et"od sed * #,

6&ile (S A= S2) 3

@ritica Section

S2 = not (S)3

7<4 Which one of the following statements escri0es the !ro!erties achieve"#$%T& '( 2)1)*(9) /utual exclusion but not 3rogress(8) #rogress but not mutual exclusion(;) Neither mutual exclusion nor 3rogress(D) 8oth mutual exclusion and 3rogress

 9nswer (9):t can be easily observed that the /utual Jxclusion requirement is satisfied by the abovesolution! #' can enter critical section only if ' is not equal to ! and # can enter criticalsection only if ' is equal to .#rogress Requirement is not satisfied. 2et us first see definition of #rogress Requirement.

 Progress Requirement: :f no 3rocess is executing in its critical section and there exist some3rocesses that wishes to enter their critical section! then the selection of the 3rocesses that

 will enter the critical section next cannot be 3ost3oned indefinitely.:f #' or # want to re@enter the critical section! then they cannot even if there is other 3rocessrunning in critical section.

32* n which one of the following !age re!lacement !olicies 5ela>s anomalma occr"(9) :I(8) I3timal(;) 2R>(D) /R>

 9nswer (9)8elady1s anomaly 3roves that it is 3ossible to have more 3age faults when increasing thenumber of 3age frames while using the irst in irst Iut (:I) 3age re3lacement algorithm.

33* The essential content#s* in each entr of a !age ta0le is H are(9) =irtual 3age number(8) #age frame number(;) 8oth virtual 3age number and 3age frame number(D) 9ccess right information

 9nswer (8) 9 3age table entry must contain #age frame number. =irtual 3age number is ty3ically used asindex in 3age table to get the corres3onding 3age frame number. ee this for details.

34* 'onsier a sstem with 4 t!es of resorces D1 #3 nits* D2 #2 nits* D3 #3nits* D4 #2 nits*. % non-!reem!tive resorce allocation !olic is se. %t angiven instance a re:est is not entertaine if it cannot 0e com!letel satisfie.Three !rocesses 1 2 3 re:est the sorces as follows if eecteine!enentl.

#ro%ess #1

t=0B re:uests 2 units of C2

t=B re:uests unit of C

t=B re:uests 2 units of C

t=1B releases unit of C2

and unit of C.

Page 106: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 106/118

t=;B releases unit of C

t=DB re:uests 2 units of C8

t=0B ?inis&es

#ro%ess #,

t=0B re:uests 2 units of Ct=2B re:uests unit of C8

t=8B re:uests unit of C

t=>B releases unit of C

t=DB ?inis&es

#ro%ess #3

t=0B re:uests unit of C8

t=2B re:uests 2 units of C

t=1B releases 2 units of C

t=;B re:uests unit of C2

t=DB re:uests unit of Ct=B ?inis&es

7=4 Which one of the following statements is TDC& if all three !rocesses rnconcrrentl starting at time tI)"(9) 9ll 3rocesses will finish without any deadlock (8) Inly #' and # will be in deadlock.(;) Inly #' and # will be in a deadlock.(D) 9ll three 3rocesses will be in deadlock 

 9nswer (9) Ce can a33ly the following Deadlock Detection algorithm and see that there is no 3rocess waiting indefinitely for a resource. ee this for deadlock detection algorithm.

39* 'onsier a isk sstem with 1)) cliners. The re:ests to access thecliners occr in following se:ence+4 34 1) 7 1A 73 2 19 ; 2)

 %ssming that the hea is crrentl at cliner 9) what is the time taken tosatisf all re:ests if it takes 1ms to move from one cliner to a?acent one anshortest seek time first !olic is se"(9) 7,ms(8) ''7ms(;) ms(D) -*ms

 9nswer (8)+! +! '%! -! '7! -! ! ',! *! %ince shortest seek time first 3olicy is used! head will first move to +. This move will cause'*5' ms. 9fter +! head will move to % which will cause '+5' ms. 9nd so on. o cylinders are

accessed in following order +! %! '7! ',! '%! -! *! +! ! - and total time will be ('* F '+ F ' F+ F , F F ' F F F -')5' 4 ''7 ms.

3;* n the following !rocess state transition iagram for a ni!rocessor sstemassme that there are alwas some !rocesses in the rea state+ Now consierthe following statements+

Page 107: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 107/118

. f a !rocess makes a transition J it wol reslt in another !rocess makingtransition % immeiatel.. % !rocess 2 in 0locke state can make transition & while another !rocess 1is in rnning state.. The O( ses !reem!tive scheling.K. The O( ses non-!reem!tive scheling.

 Which of the a0ove statements are TDC&"(9) : and ::(8) : and :::(;) :: and :::

(D) :: and := 9nswer (;): is false. :f a 3rocess makes a transition D! it would result in another 3rocess makingtransition 8! not 9.:: is true. 9 3rocess can move to ready state when :6I com3letes irres3ective of other 3rocess

 being in running state or not.::: is true because there is a transition from running to ready state.:= is false as the I uses 3reem3tive scheduling.

37* The enterL'(#* an leaveL'(#* fnctions to im!lement critical section of a!rocess are reali<e sing test-an-set instrction as followsL

void enterE@S(F)

G  6&ile testandset(F) 3

H

void leaveE@S(F)

G

  F = 03

H

754 n the a0ove soltion is a memor location associate with the '( an isinitiali<e to ). Now consier the following statements+. The a0ove soltion to '( !ro0lem is ealock-free. The soltion is starvation free.. The !rocesses enter '( in 66O orer.

K More than one !rocess can enter '( at the same time. Which of the a0ove statements is TDC&"(9) : only (8) : and ::(;) :: and :::(D) := only 

 9nswer (9)The above solution is a sim3le test@and@set solution that makes sure that deadlock doesn1toccur! but it doesn1t use any queue to avoid starvation or to have :I order.

Page 108: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 108/118

38* % mltilevel !age ta0le is !referre in com!arison to a single level !ageta0le for translating virtal aress to !hsical aress 0ecase(9) :t reduces the memory access time to read or write a memory location.(8) :t hel3s to reduce the si0e of 3age table needed to im3lement the virtual address s3ace ofa 3rocess.(;) :t is required by the translation lookaside buffer.(D) :t hel3s to reduce the number of 3age faults in 3age re3lacement algorithms.

 9nswer (8)The si0e of 3age table may become too big (ee this) to fit in contiguous s3ace. That is why3age tables are ty3ically divided in levels.

3A* The ata 0locks of a ver large file in the Cni file sstem are allocatesing(9) contiguous allocation(8) linked allocation(;) indexed allocation(D) an extension of indexed allocation

 9nswer (D)

The >nix file system uses an extension of indexed allocation. :t uses direct blocks! singleindirect blocks! double indirect blocks and tri3le indirect blocks. ollowing diagram showsim3lementation of >nix file system. The diagram is taken from I3erating ystem;once3t  book.

4)* The an K o!erations on conting sema!hores where s is a contingsema!hore are efine as follows+

9(s) B s = s 3

  if (s I 0) t&en 6ait3

J(s) B s = s % 3

  if (s I= 0) t&en 6aeup a process 6aiting on s3

Page 109: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 109/118

764 %ssme that 0 an K0 the wait an signal o!erations on 0inar sema!horesare !rovie. Two 0inar sema!hores 0 an 0 are se to im!lement thesema!hore o!erations #s* an K#s* as follows+

9(s) B 9b(Fb)3

  s = s 3

  if (s I 0) G

  Jb(Fb) 3

  9b(Kb) 3

  H

  else Jb(Fb)3

J(s) B 9b(Fb) 3

  s = s % 3

  if (s I= 0) Jb(Kb) 3

  Jb(Fb) 3

384 The initial vales of 0 an 0 are res!ectivel (9) % and %(8) % and '(;) ' and %(D) ' and '

 9nswer (;)8oth #(s) and =(s) o3erations are 3erform #b(xb) as first ste3. :f Qb is %! then all 3rocessesexecuting these o3erations will be blocked. Therefore! Qb must be '.:f "b is '! it may become 3ossible that two 3rocesses can execute #(s) one after other(im3lying 3rocesses in critical section). ;onsider the case when s 4 '! y 4 '. o "b must be%.

41* Which of the following statements a0ot snchronos an asnchronosHO is NOT tre"

(9) 9n :R is invoked on com3letion of :6I in synchronous :6I but not in asynchronous :6I(8) :n both synchronous and asynchronous :6I! an :R (:nterru3t ervice Routine) isinvoked after com3letion of the :6I(;) 9 3rocess making a synchronous :6I call waits until :6I is com3lete! but a 3rocessmaking an asynchronous :6I call does not wait for com3letion of the :6I(D) :n the case of synchronous :6I! the 3rocess waiting for the com3letion of :6I is woken u3

 by the :R that is invoked after the com3letion of :6I 9nswer (9):n both ynchronous and 9synchronous! an interru3t is generated on com3letion of :6I. :nynchronous! interru3t is generated to wake u3 the 3rocess waiting for :6I. :n

 9synchronous! interru3t is generated to inform the 3rocess that the :6I is com3lete and itcan 3rocess the data from the :6I o3eration. ee this for more details.

 % !rocess eectes the following coe

for (i = 03 i I n3 i%%) for()3

374 The total nm0er of chil !rocesses create is(9) n(8) ?n @ '

Page 110: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 110/118

(;) ?n(D) ?(nF') @ '

 9nswer (8)

  ?0 // 5&ere 6ill be c&ild process created by first

for

  / 7  ? ? // 5&ere 6ill be 2 c&ild processes created by

second for

  / 7 / 7

 ?2 ?2 ?2 ?2 // 5&ere 6ill be 8 c&ild processes created by

t&ird for

/ 7 / 7 / 7 / 7

 ............... // and so on

334 :f we sum all levels of above tree for i 4 % to n@'! we get ?n @ '. o there will be ?n B ' child3rocesses.

43* Which of the following is NOT tre of ealock !revention an ealockavoiance schemes"(9) :n deadlock 3revention! the request for resources is always granted if the resulting state issafe(8) :n deadlock avoidance! the request for resources is always granted if the result state issafe(;) Deadlock avoidance is less restrictive than deadlock 3revention(D) Deadlock avoidance requires knowledge of resource requirements a 3riori

 9nswer (9)Deadlock 3revention scheme handles deadlock by making sure that one of the four necessaryconditions donSt occur. :n deadlock 3revention! the request for a resource may not be grantedeven if the resulting state is safe.

44* % !rocessor ses 3; 0it !hsical aresses an 32 0it virtal aresses witha !age frame si<e of 4 =0tes. &ach !age ta0le entr is of si<e 4 0tes. % threelevel !age ta0le is se for virtal to !hsical aress translation where the

 virtal aress is se as follows 8its %@' are used to index into the first level 3age table 8its '@7 are used to index into the second level 3age table 8its '@% are used to index into the third level 3age table! and 8its %@'' are used as offset within the 3ageThe nm0er of 0its re:ire for aressing the net level !age ta0le #or !ageframe* in the !age ta0le entr of the first secon an thir level !age ta0les areres!ectivel(9) %! % and %(8) +! + and +

(;) +! + and %(D) ,! , and + 9nswer (D) =irtual address si0e 4 bits#hysical address si0e 4 * bits#hysical memory si0e 4 ?* bytes#age frame si0e 4 +M bytes 4 ?' bytesNo. of bits required to access 3hysical memory frame 4 * @ ' 4 +o in third level of 3age table! + bits are required to access an entry.7 bits of virtual address are used to access second level 3age table entry and si0e of 3ages in

Page 111: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 111/118

second level is + bytes. o si0e of second level 3age table is (?7)5+ 4 ?'' bytes. :t meansthere are (?*)6(?'') 3ossible locations to store this 3age table. Therefore the second 3agetable requires , bits to address it. imilarly! the third 3age table needs , bits to address it.

49* 'onsier a isk !ack with 1; srfaces 128 tracks !er srface an 29;sectors !er track. 912 0tes of ata are store in a 0it serial manner in a sector.The ca!acit of the isk !ack an the nm0er of 0its re:ire to s!ecif a!articlar sector in the isk are res!ectivel+(9) ,* /byte! '7 bits(8) ,* /byte! bits(;) ,' /byte! % bits(D) *+ Hbyte! bits

 9nswer (9);a3acity of the disk 4 '* surfaces Q ' tracks Q ,* sectors Q ,' bytes 4 ,* /bytes.To calculate number of bits required to access a sector! we need to know total number ofsectors. Total number of sectors 4 '* surfaces Q ' tracks Q ,* sectors 4 ?'7o the number of bits required to access a sector is '7.

4;* $ro! 1 contains some 'C scheling algorithms an $ro! 2 contains

some a!!lications. Match entries in $ro! 1 to entries in $ro! 2.

,3.   Lroup , Lroup ,,

,4. (9) Lang Sc&eduling () Luaranteed Sc&eduling

,5. (M) Cate onotonic Sc&eduling (2) Cealtime Sc&eduling

,6. (C) ?air S&are Sc&eduling () 5&read Sc&eduling

3=4 (9) # B K B R B '(8) # B ' K B R B (;) # B K B R B '(D) # B ' K B R B

 9nswer (9)Hang scheduling for 3arallel systems that schedules related threads or 3rocesses to run

simultaneously on different 3rocessors.Rate monotonic scheduling is used in real@time o3erating systems with a static@3riorityscheduling class. The static 3riorities are assigned on the basis of the cycle duration of the

 AobL the shorter the cycle duration is! the higher is the Aob1s 3riority.air hare cheduling is a scheduling strategy in which the ;#> usage is equally distributedamong system users or grou3s! as o33osed to equal distribution among 3rocesses. :t is alsoknown as Huaranteed scheduling.

47* %n o!erating sstem ses (hortest Demaining Time first #(DT* !rocessscheling algorithm. 'onsier the arrival times an eection times for thefollowing !rocessesL

,. 9rocess <ecution time "rrival time

,/. 9 20 030. 92 21 1

31. 9 0 0

3,. 98 1 81

994 What is the total waiting time for !rocess 2"(9) ,(8) ',(;) +%(D) ,,

Page 112: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 112/118

 9nswer (8) 9t time %! #' is the only 3rocess! #' runs for ', time units. 9t time ',! # arrives! but #' has the shortest remaining time. o #' continues for , moretime units.

 9t time %! # is the only 3rocess. o it runs for '% time units 9t time %! # is the shortest remaining time 3rocess. o it runs for '% time units 9t time +%! # runs as it is the only 3rocess. # runs for , time units. 9t time +,! # arrives! but # has the shortest remaining time. o # continues for '% moretime units.# com3letes its ececution at time ,,

34. 5otal 6aiting time for 92 = @omplition time ("rrival time %

<ecution time)

35.   = 11 (1 % 21)

36.   = 1

37.  

954 48* % virtal memor sstem ses 6irst n 6irst Ot #66O* !age re!lacement!olic an allocates a fie nm0er of frames to a !rocess. 'onsier thefollowing statements++ ncreasing the nm0er of !age frames allocate to a !rocess sometimesincreases the !age falt rate.@+ (ome !rograms o not ehi0it localit of reference. Which one of thefollowing is TDC&"(9) 8oth # and K are true! and K is the reason for #(8) 8oth # and K are true! but K is not the reason for #.(;) # is false! but K is true(D) 8oth # and K are false.

 9nswer (8)# is true. :ncreasing the number of 3age frames allocated to 3rocess may increases the no. of3age faults (ee8elady1s 9nomaly ).K is also true! but K is not the reason for@# as 8elady1s 9nomaly occurs for some s3ecific3atterns of 3age references.

4A* % single !rocessor sstem has three resorce t!es an which areshare 0 three !rocesses. There are 9 nits of each resorce t!e. 'onsier thefollowing scenario where the colmn alloc enotes the nm0er of nits of eachresorce t!e allocate to each !rocess an the colmn re:est enotes thenm0er of nits of each resorce t!e re:este 0 a !rocess in orer tocom!lete eection. Which of these !rocesses will finish ,%(T"

alloc request Q " U Q " U #% ' ' ' % #' % ' % ' # ' ' % (9) #%(8) #'(;) #(D) None of the above! since the system is in a deadlock 

 9nswer (;)Ince all resources (,! + and instances of Q! " and U res3ectively) are allocated! %! ' and instances of Q! " and U are left. Inly needs of #' can be satisfied. o #' can finish itsexecution first. Ince #' is done! it releases ! ' and units of Q! " and U res3ectively. 9mong#% and #! needs of #% can only be satisfied. o #% finishes its execution. inally! # finishesits execution.

9)* Two !rocesses 1 an 2 nee to access a critical section of coe. 'onsierthe following snchroni<ation constrct se 0 the !rocesses+Gere wants1 an

Page 113: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 113/118

 wants2 are share varia0les which are initiali<e to false. Which one of thefollowing statements is TDC& a0ot the a0ove constrct"

65 #' 56 while (true) V wants' 4 true while (wants 44 true) 65 ;ritical ection 56 wants'4false W 65 Remainder section 56 65 # 56 while (true) V wants 4 true while(wants'44true) 65 ;ritical ection 56 wants 4 false W 65 Remainder section 56 (9) :t doesnot ensure mutual exclusion.(8) :t does not ensure bounded waiting.(;) :t requires that 3rocesses enter the critical section in strict alternation.(D) :t does not 3revent deadlocks! but ensures mutual exclusion.

 9nswer (D)The above synchroni0ation constructs don1t 3revent deadlock. Chen both wants' and wants

 become true! both #' and # stuck forever in their while loo3s waiting for each other tofinish.

91* 'onsier the following statements a0ot ser level threas an kernel levelthreas. Which one of the following statement is 6%,(&"(9) ;ontext switch time is longer for kernel level threads than for user level threads.(8) >ser level threads do not need any hardware su33ort.

(;) Related kernel level threads can be scheduled on different 3rocessors in a multi@3rocessor system.(D) 8locking one kernel level thread blocks all related threads.

 9nswer (D)ince kernel level threads are managed by kernel! blocking one thread doesn1t cause allrelated threads to block. :t1s a 3roblem with user level threads

92* 'onsier three 'C-intensive !rocesses which re:ire 1) 2) an 3) timenits an arrive at times ) 2 an ; res!ectivel. Gow man contet switchesare neee if the o!erating sstem im!lements a shortest remaining time firstscheling algorithm" Jo not cont the contet switches at time <ero an at theen.(9) '

(8) (;) (D) +

 9nswer (8)2et three 3rocess be #%! #' and # with arrival times %! and * res3ectively and ;#> bursttimes '%! % and % res3ectively. 9t time %! #% is the only available 3rocess so it runs. 9t time! #' arrives! but #% has the shortest remaining time! so it continues. 9t time *! # arrives!

 but #% has the shortest remaining time! so it continues. 9t time '%! #' is scheduled as it is theshortest remaining time 3rocess. 9t time %! # is scheduled. Inly two context switches areneeded. #% to #' and #' to #.

93* % com!ter sstem s!!orts 32-0it virtal aresses as well as 32-0it!hsical aresses. (ince the virtal aress s!ace is of the same si<e as the!hsical aress s!ace the o!erating sstem esigners ecie to get ri of the

 virtal memor entirel. Which one of the following is tre"(9) Jfficient im3lementation of multi@user su33ort is no longer 3ossible(8) The 3rocessor cache organi0ation can be made more efficient now (;) <ardware su33ort for memory management is no longer needed(D) ;#> scheduling can be made more efficient now 

 9nswer (;)or su33orting virtual memory! s3ecial hardware su33ort is needed from /emory/anagement >nit. ince o3erating system designers decide to get rid of the virtual memoryentirely! hardware su33ort for memory management is no longer needed

Page 114: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 114/118

94* % 'C generates 32-0it virtal aresses. The !age si<e is 4 =5. The!rocessor has a translation look-asie 0ffer #T,5* which can hol a total of 128!age ta0le entries an is 4-wa set associative. The minimm si<e of the T,5 tagis+(9) '' bits(8) ' bits(;) ', bits(D) % bits

 9nswer (;)i0e of a 3age 4 +M8 4 ?'Total number of bits needed to address a 3age frame 4 B ' 4 %:f there are On1 cache lines in a set! the cache 3lacement is called n@way set associative. inceT28 is + way set associative and can hold total ' (?-) 3age table entries! number of sets incache 4 ?-6+ 4 ?,. o , bits are needed to address a set! and ', (% B ,) bits are neededfor tag.

99* 'onsier three !rocesses #!rocess i ) 1 2 res!ectivel* with com!te time 0rsts 2 4 an 8 time nits. %ll !rocesses arrive at time <ero. 'onsier the

longest remaining time first #,DT6* scheling algorithm. n ,DT6 ties are 0roken 0 giving !riorit to the !rocess with the lowest !rocess i. The averagetrn aron time is+(9) ' units(8) '+ units(;) ', units(D) '* units

 9nswer (9)2et the 3rocesses be 3%! 3' and 3. These 3rocesses will be executed in following order.

  p2 p p2 p p2 p0 p p2 p0 p p2

0 8 1 > ; D 0 2 8

964 Turn around time of a 3rocess is total time between submission of the 3rocess and itscom3letion.Turn around time of 3% 4 ' ('@%)Turn around time of 3' 4 ' ('@%)Turn around time of 3 4 '+ ('+@%)

 9verage turn around time is ('F'F'+)6 4 '.

9;* 'onsier three !rocesses all arriving at time <ero with total eection timeof 1) 2) an 3) nits res!ectivel. &ach !rocess s!ens the first 2)B ofeection time oing HO the net 7)B of time oing com!tation an the last1)B of time oing HO again. The o!erating sstem ses a shortest remainingcom!te time first scheling algorithm an scheles a new !rocess either

 when the rnning !rocess gets 0locke on HO or when the rnning !rocess

finishes its com!te 0rst. %ssme that all HO o!erations can 0e overla!!e asmch as !ossi0le. 6or what !ercentage of time oes the 'C remain ile"(9) %X(8) '%.*X(;) %.%X(D) 7.+X

 9nswer (8)2et three 3rocesses be 3%! 3' and 3. Their execution time is '%! % and % res3ectively. 3%s3ends first time units in :6I! - units of ;#> time and finally ' unit in :6I. 3' s3ends first +units in :6I! '+ units of ;#> time and finally units in :6I. 3 s3ends first * units in :6I! '

Page 115: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 115/118

units of ;#> time and finally units in :6I.

 idle p0 p p2 idle

0 2 2 88 8;

5otal time spent = 8;

,dle time = 2 % = 1

9ercentage of idle time = (1/8;)*00 = 0.> $

97* The atomic fetch-and-set x, y instrction nconitionall sets the memorlocation to 1 an fetches the ol vale of in withot allowing anintervening access to the memor location . consier the followingim!lementation of an K fnctions on a 0inar sema!hore .

void 9 (binaryEsemap&ore *s) G

  unsigned y3

  unsigned * = (svalue)3  do G

  fetc&andset + y3

  H 6&ile (y)3

H

void J (binaryEsemap&ore *s) G

  Svalue = 03

H

:84 Which one of the following is tre"(9) The im3lementation may not work if context switching is disabled in #.

(8) :nstead of using fetch@and@set! a 3air of normal load6store can be used(;) The im3lementation of = is wrong(D) The code does not im3lement a binary sema3hore

 9nswer (9)2et us talk about the o3eration #(). :t stores the value of s in x! then it fetches the old value ofx! stores it in y and sets x as '. The while loo3 of a 3rocess will continue forever if some other3rocess doesn1t execute =() and sets the value of s as %. :f context switching is disabled in #!the while loo3 will run forever as no other 3rocess will be able to execute =().

98* 'onsier the following sna!shot of a sstem rnning n !rocesses. rocess iis holing i instances of a resorce D 1 PI i PI n. crrentl all instances of Dare occ!ie. 6rther for all i !rocess i has !lace a re:est for an aitional

 i instances while holing the i instances it alrea has. There are eactl two!rocesses ! an : sch that ! I : I ). Which one of the following can serve asa necessar conition to garantee that the sstem is not a!!roaching aealock"(9) min (Q3! Qq) max ("k) where k Y4 3 and k Y4 q(8) Q3 F Qq P4 min ("k) where k Y4 3 and k Y4 q(;) max (Q3! Qq) P '(D) min (Q3! Qq) P '

 9nswer (8)ince both 3 and q don1t need additional resources! they both can finish and release Q3 F Qq

Page 116: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 116/118

resources without asking for any additional resource. :f the resources released by 3 and q aresufficient for another 3rocess waiting for "k resources! then system is not a33roachingdeadlock.

9A* Normall ser !rograms are !revente from hanling HO irectl 0 HOinstrctions in them. 6or 'Cs having e!licit HO instrctions sch HO!rotection is ensre 0 having the HO instrctions !rivilege. n a 'C withmemor ma!!e HO there is no e!licit HO instrction. Which one of thefollowing is tre for a 'C with memor ma!!e HO"(a) :6I 3rotection is ensured by o3erating system routine(s)(b) :6I 3rotection is ensured by a hardware tra3(c) :6I 3rotection is ensured during system configuration(d) :6I 3rotection is not 3ossible

 9nswwer (a)

/emory ma33ed :6I means! accessing :6I via general memory access as o33osed tos3eciali0ed :I instructions. 9n exam3le!

41.   unsigned int volatile const *papped"ddress const =

(unsigned int *)0003

o! the 3rogrammer can directly access any memory location directly. To 3revent such anaccess! the I (kernel) will divide the address s3ace into kernel s3ace and user s3ace. 9nuser a33lication can easily access user a33lication. To access kernel s3ace! we need systemcalls (tra3s).

;)* What is the swa! s!ace in the isk se for"(a) aving tem3orary html 3ages(b) aving 3rocess data(c) toring the su3er@block (d) toring device drivers

 9nswer (b)wa3 s3ace is ty3ically used to store 3rocess data..

;1* ncreasing the D%M of a com!ter t!icall im!roves !erformance 0ecase+(a) =irtual memory increases(b) 2arger R9/s are faster(c) ewer 3age faults occur(d) ewer segmentation faults occur

 9nswer (c)

;2* (!!ose n !rocesses 1 /. n share m ientical resorce nits which can 0e reserve an release one at a time. The maimm resorce re:irement of!rocess i is (i where (i Q ). Which one of the following is a sfficientconition for ensring that ealock oes not occr"

 9nswer (c):n the extreme condition! all 3rocesses acquire i@' resources and need ' more resource. ofollowing condition must be true to make sure that deadlock never occurs.

Page 117: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 117/118

  m

The above ex3ression can be written as following.  (m F n)

;3* 'onsier the following coe fragment+ 

if (for() == 0)

  G a = a % 13 printf(O$d+$d7nP+ a+ a)3 H

  else G a = a Q13 printf(O$d+ $d7nP+ a+ a)3 H

,et v 0e the vales !rinte 0 the !arent !rocess an 0e the vales!rinte 0 the chil !rocess. Which one of the following is TDC&"(a) u 4 x F '% and v 4 y (b) u 4 x F '% and v Y4 y 

(c) u F '% 4 x and v 4 y (d) u F '% 4 x and v Y4 y  9nswer (c)fork() returns % in child 3rocess and 3rocess :D of child 3rocess in 3arent 3rocess.:n ;hild (x)! a 4 a F ,:n #arent (u)! a 4 a B ,Therefore x 4 u F '%.The 3hysical addresses of Oa1 in 3arent and child must be different. 8ut our 3rogram accesses

 virtual addresses (assuming we are running on an I that uses virtual memory). The child3rocess gets an exact co3y of 3arent 3rocess and virtual address of Oa1 doesn1t change in child3rocess. Therefore! we get same addresses in both 3arent and child.

 

:34 This im!lementation

(9) fails as 2 can overflow (8) fails as 2 can take on a non@0ero value when the lock is actually available(;) works correctly but may starve some 3rocesses(D) works correctly without starvation

 9nswer (8)Take closer look the below while loo3.

  6&ile (?etc&E"ndE"dd(4+))

  4 = 3 // " 6aiting process can be &ere Rust after

// t&e loc is released+ and can mae 4 = .

:94 ;onsider a situation where a 3rocess has Aust released the lock and made 2 4 %. 2et there beone more 3rocess waiting for the lock! means executing the 9cquire2ock() function. Eustafter the 2 was made %! let the waiting 3rocesses executed the line 2 4 '. Now! the lock isavailable and 2 4 '. ince 2 is '! the waiting 3rocess (and any other future coming 3rocesses)can not come out of the while loo3.The above 3roblem can be resolved by changing the 9cuire2ock() to following.

"c:uire4oc(4)G

  6&ile (?etc&E"ndE"dd(4+))

  G // -o Not&ing H H

Page 118: OS Study Material

7/24/2019 OS Study Material

http://slidepdf.com/reader/full/os-study-material 118/118

 

PPPPPPPPPPTHDQD(PPPPPPPPP3@@ THD =D%T