OS-UNIT-I
OS-UNIT-I
IIIB.TECH, I-SEMCSE
UNIT-I
OperatingSystemsOverview:Operatingsystemfunctions,Operatingsystemstructure,operatingsystems
Operations, protection and security, Computing Environments, Open- Source Operating Systems
System Structures:OperatingSystemServices, User andOperating-SystemInterface, systemscalls,
TypesofSystem Calls, system programs, operatingsystemstructure, operatingsystem debugging,
System Boot.
OperatingSystemsOverview:
Computersoftwarecanbedividedintotwomaincategories:
1. ApplicationSoftware
2.SystemSoftware
1.ApplicationSoftware
Application software consists of the programs for performing tasks particular to the machine’s utilization. This
softwareisdesignedtosolveaparticularproblemforusers.
Examples of application software include spreadsheets, database systems,desktop publishing systems , program
development software and games.
2.SystemSoftware
On the other hand system software is more transparent and less noticed by the typical computer user. This software
provides a general programming environment in which programmers can create specific applications tosuit their needs. This
environment provides new functions that are not available at the hardware level and performs
tasksrelatedtoexecutingtheapplicationprograms.Systemsoftwareactsasaninterfacebetweenthehardwareof the computer and
the application software that users need to run on the computer.
ThemostimportanttypeofsystemsoftwareistheOperatingSystem.
⚫ Thepurposeofanoperatingsystemistoprovideanenvironmentinwhichausermay executetheir
applicationprograms.
⚫ Operating Systems are viewed as resource managers. The main resource is the computer hardware in the form
of processors, storage devices, input/output devices, communication devicesand data.
⚫ Aprogramthatactsasanintermediarybetweenauserofacomputerandthecomputerhardware
1
⚫ Providesaninterfacebetweenthecomputerhardwareandtheprogrammerthat simplifiesandmakes feasible the
creation ,coding ,debugging and maintenance of application programs .
⚫ Computer system consisting of hardware software and data . The Operating System provides the means
forproperuseoftheseresourcesintheoperationofthecomputersystem.
⚫ AnOperatingSystemissimilar togovernment.Likeagovernmentitperformsnousefulfunctionby itself. It simply
provides an environmentwithin which other programs can do useful work
ThepurposeofanOperatingSystemistoprovideanenvironmentinwhichuserscanexecutetheir programs
inaconvenientandefficientmanner.
ComputerSystemStructure
Computersystemcanbedividedintofourcomponents
Hardware–providesbasiccomputingresourcesCPU,memory,I/Odevices
Operatingsystem-Controlsandcoordinatesuseofhardwareamongvariousapplicationsandusers
Application programs –define theways in which the system resources are used to solve thecomputingproblemsof the
users-Word processors, compilers, web browsers, database systems,video games
Users-People,machines,othercomputers
Architecture of
Computer System
2
TwoViewsofOperatingSystem
TheRoleofOperatingSystemcanbeviewedintwoways
1.User'sView
2.SystemView
User's View :
Theuserviewofthecomputerdependsontheinterfacebeingused
i)Some users may use PC’s: Users sit in front of a PC Such systems are designed for one user to monopolize
itsresources.Inthesecasestheoperatingsystemisdesignedmostlyforeaseofuse(convenience)withsome attention paid to
performance and none paid to resource utilization.
ii)Some users may use a terminal connected to amainframe or minicomputers: The multiple users share resources and may
exchange information . In thesecases the operating system is designed to maximize resource utilization-sothat all available CPU
time memory& I/O are used efficiently and no user takes more than his share.
iii) Some users sit at PC connected to networks of other workstations and servers:These users have dedicated
resources at their disposal but they also share resources such as networking and servers-file computer and print servers.
Therefore theiroperatingsystemisdesignedtocompromisebetweenindividualusability and resource utilization.
3
iv) Recently many varieties of handheld computershave come into fashion. Most of these devices are standalone units
for individualusers.Some are connected tonetworks either directly by wire or (more often) through wireless modems and
networking. Because of power speed and interface limitationsthey perform relatively few remote operations. Their operating
systems are designed mostly for individual usability but performance per unit of battery life is important as well.
v) Some computers have little or no user view. For example embedded computers in home devices and automobiles
may have numeric keypads and may turn indicator lights on or off toshow status but they and their operating systems are
designed primarily to run without user intervention
SystemView
Fromthecomputer'spointofviewoperatingsystemviewedasaresourceallocator.
A computer system has many resources (hardware and software) that may be required to solve a problem: CPU
timememoryspacefilesstoragespaceinput/outputdevicesetc.Theoperatingsystemactsasthemanagerof these resources and
allocates them tospecific programs and users as necessary for their tasks.
Fromthecomputer'spointofviewoperatingsystemviewedasacontrolprogram.
The OS controls and co-ordinates the execution ofuser programs to preventerrors and improper use ofthe
computer.ItisespeciallyconcernedwiththeoperationandcontrolofI/Odevices.
OperatingSystemgoalsorObjectives:
TherearetwomaingoalsofanOperatingSystem:-
1.Convenience:- The primary goal of OS is to make computer system easier for user i.e. OS makes
interactionb/wuserandhardware.
2. Efficiency:-Thesecondarygoal of OS is toallocate the system resourcesto variousapplicationprogram as
efficientaspossible.
Theprimarygoalofsomeoperatingsystemisconveniencefortheuser.
This exists because they are supposed to make it easier to compute them without them. This view is particularly
clearwhenyoulookatOperatingSystemsforsmallPCs.
While the primary goalof some other operating systemis efficient operation of the computer system. These are used for
largesharedmultiuser systems.These systems are expensiveso itis desirableto make themas efficient as possible.
These two goals- convenience and efficiency are sometimes contradictory In past the efficiency was often more important than
convenience. Thus much of the Operating System theory concentrates on optimal use of the computingresources.
OperatingSystemFunctions:
FollowingaresomeofimportantfunctionsofanoperatingSystem
⚫ ProvidingUserInterface
⚫ MemoryManagement
⚫ ProcessorManagement
⚫ ProcessManagement
⚫ DeviceManagement
⚫ FileManagement
4
⚫ ProtectionandSecurity
⚫ Controloversystemperformance
⚫ Jobaccounting
⚫ Errordetectingaids
⚫ Coordinationbetweenothersoftwareandusers
ProvidingUserInterface
OSprovidesaninterfacetotheusertointeractwithacomputeras
Graphical user interface (GUI)
Mostcommoninterface Windows
OS X, Gnome KDE Uses a mouse
to control objects Uses a desktop
Shortcuts to open programs or documents Task
switching
Dialogboxesallowdirectedinput
Commandlineinterfaces
Older interface DOS,
Linux, UNIX
Usertypescommandsataprompt User must
remember all commands
IncludedinallGUIs
5
MemoryManagement
MemorymanagementreferstomanagementofPrimaryMemoryorMainMemory.Mainmemoryprovidesafast storagethat
canbeaccesseddirectlybytheCPU. Fora programtobeexecutedit must beinthemainmemory.
AnOperatingSystemdoesthefollowingactivitiesformemorymanagement:
Keepstrackofprimarymemoryi.e.whatpartofitareinusebywhomwhatpartarenotinuse.
InmultiprogrammingtheOSdecideswhichprocesswillgetmemorywhenandhowmuch.
Allocatesthememorywhenaprocessrequestsit.
De-allocatesthememorywhenaprocessnolongerneedsitorhasbeenterminated.
ProcessorManagement
In multiprogramming environment the OS decides which process gets the processor when and for how much time.
ThisfunctioniscalledprocessororCPUScheduling.
AnOperatingSystemdoesthefollowingactivitiesforprocessormanagement−
Keepstracksofprocessorandstatusofprocessor.Theprogramresponsibleforthistaskisknown astrafficcontroller.
Allocatestheprocessor(CPU)toaprocess.
De-allocatesprocessorwhenaprocessisnolongerrequired.
ProcessManagement
Aprocessisaprograminexecution.
TheOSisresponsibleforthefollowingactivitiesoftheprocessmanagement
• Creating&destroyingoftheuser&systemprocess.
• AllocatingH/wresourcesamongtheprocesses.
• Controllingtheprogressoftheprocess.
• Providesmechanismsforprocesssynchronizationand
6
communication.
• Providesmechanismfordeadlockhandling.
DeviceManagement
AnOperatingSystemmanagesdevicecommunicationviatheirrespectivedrivers.
Itdoesthefollowingactivitiesfordevicemanagement:
Keepstracksofalldevices.ProgramresponsibleforthistaskisknownastheI/Ocontroller.
Decideswhichprocessgetsthedevicewhenandforhowmuchtime.
Allocatesthedeviceintheefficientway.
De-allocatesdevices.
FileManagement
A file system isnormally organized into directories for easy navigation and usage. These directories may
containfilesandotherdirectories.
TheOSisresponsibleforthefollowingactivitiesoftheFileManagement
Ithelpstocreatenewfilesincomputersystemandplacingthematthespecificlocations.
Ithelpsineasilyandquicklylocatingthesefilesincomputersystem.
Itmakestheprocessofsharingofthefilesamongdifferentusersveryeasilyanduserfriendly.
It helpsto stores the files in separate folders known as directories. These directories help users to search
filequicklyortomanagethefilesaccordingtotheirtypesoruses.
Ithelpstheusertomodifythedataoffilesortomodifythenameofthefileinthedirectories.
ProtectionandSecurity
Security : Itinvolves guarding ofauser’s data andprograms againstinterference by externalentities,e.g. unauthorizedpersons.
ex:Restrictingtheaccessofsystemwithfirewallsandauthentication
Protection : It involves guarding a user’s data and programs against interference by other authorized users of the system.
ex:Restrictingtheaccessofinformationwithpermissions
Controloversystemperformance: Recordingdelaysbetween request fora service and response from the system.
JobandResourceaccounting−Keepingtrackoftimeandresourcesusedbyvariousjobsandusers.
Errordetectingaids−Productionofdumps,traces,errormessages,andotherdebugginganderrordetecting aids.
Coordination between other softwares and users− Coordinationandassignment of compilers, interpreters,
assemblersandothersoftwaretothevarioususersofthecomputersystem
Handlingnetworkcommunications:Providingcommunicationb/wtwocomputers
OperatingSystemStructure
7
Non-multiprogrammedsystem’sworking–
• In a non multi programmed system, As soon as one job leaves the CPU and goes for some other task (say I/O ), the
CPU becomes idle.The CPU keepswaiting andwaiting untilthis job (which was executing earlier) comes back and
resumes its execution with the CPU.So CPU remains free for allthis while.
• Now it has a drawback that the CPU remains idle for a very long period of time. Also, other jobs which are waiting to
be executed might not get a chance to execute because the CPU is still allocated to the earlier job.
This poses a very serious problem that even though other jobs are ready to execute, CPU is not
allocatedtothemastheCPUisallocatedtoajobwhichisnotevenutilizingit(asitisbusyinI/Otasks).
• ItcannothappenthatonejobisusingtheCPUforsay1hourwhiletheothershavebeenwaitinginthe queue for 5 hours. To
avoid situations like this and come up with efficient utilization of CPU, the concept of multi programming came up.
ThemainideaofmultiprogrammingistoutilizetheCPUefficiently.
Multiprogrammedsystem’sworking–
In a multi-programmed system, as soon as one job goes for an I/Otask, the Operating System interrupts
thatjob,choosesanotherjobfromthejobpool(waitingqueue),givesCPUtothisnewjobandstartsits execution.
ThepreviousjobkeepsdoingitsI/O operationwhilethisnewjobdoesCPUboundtasks.Nowsaythe second job also goes
for an I/Otask, the CPU chooses a third joband starts executing it. Assoon as a job completes its I/O operation and
comes back for CPU tasks, the CPU is allocated to it.
In this way, no CPU time is wasted by the system waiting for the I/O task to be completed. Therefore, the
ultimategoal of multi programming is to keep the CPU busy as long asthere are processes readyto execute. This way,
multiple programscan be executed on a single processor byexecuting a partof a program at onetime, a part of another
program after this, then apart of another program and so on, hence executing multiple programs. Hence, the CPU
never remains idle.
8
31
Tuesday,July
MemoryLayoutforMultiprogrammedSystem
9
Multitaskingsystem’sworking–
In a time sharing system, each process is assigned some specific quantum of time for which a process is meant to
execute. Say there are 4 processes P1, P2, P3, P4 ready to execute. So each of them are assigned some time
quantum for which they will execute e.g time quantum of 5 nanoseconds (5 ns).
Asoneprocessbeginsexecution(sayP2),itexecutesforthatquantum oftime(5ns).After5 nstheCPU starts the
execution of the other process (say P3) for the specified quantum of time.
Thus the CPU makes theprocesses to share time slices between them and execute accordingly. As soon as time
quantum of one process expires, another process begins its execution.
Here also basically a context switch is occurring but it is occurring so fast that the user is ableto interact
witheachprogramseparately whileitis running.
This way, the user is given the illusion that multiple processes/ tasks are executing simultaneously. But
actuallyonlyoneprocess/taskisexecutingataparticularinstantoftime.
10
Multiprocessing
Inauni-processorsystem,onlyoneprocessexecutesatatime. Multiprocessing is the use of two or more CPUs
(processors) within a single Computer system. The termalso refers tothe
abilityofasystemtosupportmorethanoneprocessorwithinasinglecomputersystem.
Multiprocessingsystem’sworking
⚫ With the help ofmultiprocessing, many processes can be executed simultaneously. Say processes P1, P2, P3 andP4 are
waiting forexecution. Nowin a single processor system, firstly one process will execute, then the other, then theother
andsoon.
⚫ But with multiprocessing, each process can be assigned to a different processor for its execution. If its a dual-core
processor (2 processors), twoprocesses can be executed simultaneously andthus will
betwotimesfaster,similarlyaquadcoreprocessorwillbefourtimesasfastasasingleprocessor
11
Multithreading–
AthreadisabasicunitofCPUutilization.Multithreadingisanexecutionmodelthatallowsasingleprocessto
havemultiplecodesegments(i.e.,threads)runningconcurrentlywithinthe“context”ofthatprocess.
e.g. VLC media player, where one thread is used for opening the VLC media player, one thread for playing a
particularsongandanotherthreadforaddingnewsongstotheplaylist
12
Operating-SystemOperations
ModernoperatingsystemsareinterruptdriventhatmeansIftherearenoprocessestoexecute,noI/O devices
toservice,andnousers towhom torespond,
Anoperatingsystemwillsitquietly,waitingforsomethingtohappen.
Events are almost always signaled by the occurrence of aninterrupt or a trap. what is
trap ?
Atrap(oranexception)isasoftware-generatedinterruptcausedeitherbyanerror(forexample,divisionbyzero or invalid memory
access) or by a specific request from a user programto theoperating-system to get the services of the OS.
Theinterrupt-drivennatureof anoperatingsystemdefinesthat system'sgeneral structure.
Foreachtypeofinterrupt,separatesegmentsofcodeintheoperatingsystemdeterminewhatactionshouldbetaken. An interrupt
service routine is provided that is responsible for dealing with the interrupt.
Since the operating system and theusers share the hardware and software resources of the computer system, we need to make
sure thatan error in a user program could cause problems only for the one program thatwas running. With sharing, many
processes could be adversely affected by a bug in one program. For example, if a process gets stuckin an infinite loop, this loop
could prevent the correct operation of manyother processes.
A properly designed operating system must ensure that an incorrect (or malicious) program cannot cause other
programs to execute incorrectly.
13
Dual-ModeOperation
In order to ensure the proper execution of the operating system, we must be able to distinguish between the
executionofoperating-systemcodeanduserdefinedcode.
The approach taken by mostcomputer systems is to provide hardware supportthatallows usto differentiate among various
modes of execution.
Attheveryleast,weneedtwoseparatemodesofoperation:
usermodeandkernelmode(alsocalledsupervisormode,systemmode,orprivilegedmode).
Abit,calledthemodebit,isaddedtothehardwareofthecomputertoindicatethecurrentmode:kernel(0)oruser
(1). With the mode bit, we are able to distinguish between a task that is executed on behalf of the operating system and one
thatis executed on behalfofthe user
• Whenthecomputersystemisexecutingonbehalfofauserapplication,thesystemisinusermode.
• However, when a user application requests a service from the operating system (via a system call), it
musttransitionfromusertokernelmodeto fulfillthe request. As we shallsee, this architectural
enhancementisusefulformanyotheraspectsofsystemoperationaswell.
14
• Atsystemboottime,thehardwarestartsinkernelmode.
15
• Theoperatingsystemisthenloadedandstartsuserapplicationsinusermode.
• Whenevera trap orinterrupt occurs, the hardware switches fromuser mode to kernel mode(that is, changes the
state of the mode bit to 0).
• Thus,whenevertheoperatingsystemgainscontrolofthecomputer,itisinkernelmode.
• The system alwaysswitches to user mode (by settingthe mode bitto 1)before passing control to a user program.
TransitionfromUsertoKernelMode
Thedualmodeofoperationprovidesuswiththemeansforprotectingtheoperatingsystemfromerrant users.
We must ensure that the operating systemmaintains control over the CPU. We ustpreventauser program
fromgettingstuckinaninfiniteloop.Toaccomplishthisgoal,wecanuseatimer.Atimercanbesettointerrupt the computer after a
specified period.
Theperiodmaybefixed(forexample,1/60second)orvariable(forexample,from1millisecondto1second).
16
The operating system sets the counter. Every time the clock ticks, the counter is decremented. When the counterreaches 0, an
interrupt occurs.
Aslongasthecounterispositive,controlisreturnedtotheuserprogram.
When the counter becomes negative, the operating system terminates the program for exceeding the assigned time limit.
ProtectionandSecurity
⚫ InterferenceinresourceutilizationisaveryseriousthreatinanOS
⚫ Thenatureofthethreatdependsonthenatureofaresourceandthemannerinwhichitisused.
⚫ Themost common threats areto information stored in files because they are the most common.
OSusetwosetsoftechniquestocounterthreatstoinformationnamely:
1.Protection
2.Security
⚫ Protection :Itinvolves guardinga user’sdata and programs againstinterference by other authorized users of the
system.
ex:Restrictingtheaccessofinformationwithpermissions
⚫ Security:Itinvolvesguardingofauser’sdataandprogramsagainstinterferencebyexternalentities,
e.g.unauthorizedpersons.
ex:Restrictingtheaccessofsystemwithfirewallsandauthentication
ComputingEnvironments
• PersonalComputingEnvironment
• TimeSharingComputingEnvironment
• ClientServerComputingEnvironment
• DistributedComputingEnvironment
• Peer-to-PeerComputing
• GridComputingEnvironment
• ClusterComputingEnvironment
• Web-BasedComputing
PersonalComputingEnvironment
Personal computing is a stand alone machine. In personal computing environment, thecomplete program
residesonstandalonemachineandexecutedfromthesamemachine.Laptops,mobiledevices,printers,scannersand the
computersystemswe use at home, office are the examplesforpersonal computingenvironment
17
TimeSharingComputingEnvironment
Timesharingcomputingenvironmentisstandalonecomputerinwhichasingleusercanperformmultiple operations at a
time by using multitasking operating system. Here the processor time is divided among different
tasksandthisiscalled“Timesharing”.Forexample,ausercanlistentomusicwhilewritingsomethinginatext editor. Windows 95
and later versions of windows OS, iOS and Linux operating systems are the examples for this computingenvironment.
ClientServerComputingEnvironment
The client server environment contains two machines (Client machine and Server machine). These both machines will exchange
the informationthrough an application. Here Client isa normal computer likePC, Tablet, Mobile, etc., and Server is a powerful
computer which stores huge data and manages huge amount offile andemails,
etc.,Inthisenvironment,clientrequestsfordataandserverprovidesdatatotheclient.
18
DistributedComputingEnvironment
In the distributed computing environment, the complete functionality of a software is not on single computer but is distributed
among multiple computers. Here we use a method of computerprocessingin which different programsof an application run
simultaneously on two ormore computers. These computers communicate with each otherover a network to perform the
complete task. In distributed computing environment, the data is distributed among
differentsystemsandthatdataislogicallyrelatedtoeachother.
19
Peer-to-PeerComputing
⚫ Anothermodelofdistributedsystem
⚫ P2Pdoesnotdistinguishclientsandservers
⚫ Insteadallnodesareconsideredpeers
⚫ Mayeachactasclientserverorboth
⚫ Advantage over traditional client-serversystem is thatthe server isa bottleneck.Butin a P2P
systemservices canbeprovidedby severalnodes.
20
GridComputingEnvironment
21
Gridcomputingservescomputingresourcessuchasnetwork,server,applicationstotheindividualusers.Grid involves the loosely
coupled systems in which jobs are managed and scheduled in a distributed way. It divides a massive job in smaller chunks
andprocesses those chunks separately. Grid computing is a combination of non- centralized computing resources where each
geographically separate, independent site has its own administrative control over it.
CloudComputingEnvironment
Cloud computing is a modern computing paradigm which provides scalable and flexible IT infrastructure and
essentialservicestotheusersthroughtheinternet.
Thedifferencebetweenacloudandagridcanbeexpressedasbelow:
Resource distribution: Cloud computing is a centralized model whereas grid computing is a decentralized model where the
computation could occur over many administrative domains.
Ownership:Agrid is a collection ofcomputerswhichis owned by multiple parties in multiple locations and connected
togetherso that users can share the combined power of resources. Whereas a cloud is a collection of computers usually owned
by a single party.
Examples of Clouds: Amazon Web Services (AWS), Google App Engine. Examples of
Grids: FutureGrid.
Examples of cloud computing services: Dropbox, Gmail, Facebook, Youtube, RapidShare. Cluster
Computing Environment
Cluster computing is a collection of inter connected computers connected by LAN . These computers work together to solve
asingleproblem.In clustercomputing environment,a collection ofsystems work together asa single system. Cluster is
tightly coupled . clusters are made up of machines with similar hardware
Web-BasedComputing
Webhasbecomeubiquitous(beingpresenteverywhereatonce)
⚫ Nowloadbalancersareusedtomanagewebtrafficamongsimilarservers
⚫ Use of operating systems like Windows 95 client-side have evolved into Linux and Windows XP which can
beclientsandservers
22
Open-SourceOperatingSystems
⚫ Operatingsystemsmadeavailableinsource-codeformatratherthanjustbinaryclosed-source
⚫ StartedbyFreeSoftwareFoundation(FSF)whichhas“copyleft”GNUPublicLicense(GPL)
⚫ Copyrightsexistinordertoprotectauthorsofdocumentationorsoftwarefromunauthorizedcopyingor selling oftheir
work.A copyrightinfers thatonly with the author's permission may such activities take place.
⚫ Copyleftoverridescopyrightandpromotestheconceptthatmaterialsbefreelyused,copiedandmodified
byothers.Copyleftalsorequiresallmodifiedandextendedversionsofthematerialalsobefreely accessible, used and modified by
others.
⚫ ExamplesincludeGNU/LinuxBSDUNIX(includingcoreofMacOSX)andSunOpenSolaris,Ubuntu,
ReactOS,HaikuOS
Ubuntu
⚫ The most widely used open source data base is Ubuntu. It is a Linux basedoperating system and is distributed
free along with the source code. Its desktop looks somewhat similar to that of Windows, with window controls and
icons. There is reasonable large software support available on Ubuntu; the common applicationsinclude
MozillaFirefoxwebbrowser, LibreOfficeofficeapplicationsuite, GIMP imageeditor and so on.
23
OpenSolaris
⚫ OpenSolaris is a computer operating system developed by Sun Microsystems. It runs well on desktops, laptops, servers
and data centers. OpenSolaris is GUI based like Ubuntu and has rich graphical desktop and windows for easy
navigation.
FreeBSD
⚫ FreeBSDisanadvancedoperatingsystemforx86compatible(includingPentiumandAthlon),AMD64 compatible. It
is popular among network developers, as FreeBSD offers advanced networking, performance,
securityandcompatibilityfeatures. Most softwarethat runsonLinuxcanrun onFreeBSD withoutthe need for any
compatibility layer.
ReactOS
⚫ It is afree Windows compatible OS that offers the benefits of running Windows apps natively. Apart from being an
open-source software (its main highlight), the tool has one really cool featurethat Windows failed tooffer–
AnapplicationmanagerverymuchsimilartoLinuxpackagemanager.
HaikuOS
⚫ WhatmostuserslikeaboutthisOSisitsuniformityandcohesiveness.
⚫ To start up the operating system, one simply inserts thethumb drive into a USB port and reboot. This should not
pose a problem as most modern computers these days can be set toboot from the USB
key.TheOSisfastandresponsive.Moreover,itisequippedwithanumberofapplicationsanddemospre- installed.
SystemStructures:
OperatingSystemServices
Operating systems provide an environment for execution ofuser programs and providesservices to programs and users
1.Onesetofoperating-systemservicesprovidesfunctionsthatarehelpfultotheuser:
o Userinterface-Almostalloperatingsystemshaveauserinterface(UI).
Varies between Command-Line (CLI), Graphics User Interface (GUI),Batch 1945–
1968:Batchinterface
1969–present: Command-line user interface
1968–present: Graphical User Interface
o Program execution – The operatingsystem must be able to load a program into memory and to run that
program, end execution, either normally or abnormally (indicating error)
o I/Ooperations-ArunningprogrammayrequireI/O,whichmayinvolveafileoranI/Odevice
o File-system manipulation -The file system is of particular interest. Programs need to read and
writefilesanddirectories,createanddeletethem,searchthem,listfileInformation,permission management.
24
o Communications–Processesmayexchangeinformation,onthesamecomputerorbetween
computersoveranetwork
Communications may be via shared memory or through message passing (packets moved by the
OS)
o Errordetection–OSneedstobeconstantlyawareofpossibleerrors
MayoccurintheCPUandmemoryhardware,inI/Odevices,inuserprogram
Foreachtypeoferror,OSshouldtaketheappropriateactiontoensurecorrectandconsistent computing
o Debugging facilities can greatly enhance the user’s and programmer’s abilities to efficiently usethe system
2.Another set of OS functions exists for ensuring the efficient operation of the system itself via resourcesharing
– Resource allocation - Whenmultiple users or multiple jobs running concurrently, resources must
beallocatedtoeachofthem
• Manytypesofresources-CPUcycles,mainmemory,filestorage,I/Odevices.
– Accounting-Tokeeptrackofwhichusersusehowmuchandwhatkindsofcomputerresources
– Protection and security - The owners of information stored in a multiuser or networked computer system
may want to control use of that information, concurrent processes shouldnot interfere with each other
• Protectioninvolvesensuringthatallaccesstosystemresourcesiscontrolled
• Security of the system from outsiders requires user authentication, extends to defending
externalI/Odevicesfrominvalidaccessattempts
AViewofOperatingSystemServices
25
UserOperatingSystemInterface
UserOperatingSystemInterface–CLI
CLIorcommandinterpreterallowsdirectcommandentry
– Sometimesimplementedinkernel,sometimesbysystemsprogram
–Sometimes multiple flavors implemented – shells Bourne
shell (sh),C shell (csh),TC shell (tcsh)
Kornshell(ksh),BourneAgainshell(bash)
– Primarilyfetchesacommandfromuserandexecutesit
– Sometimescommandsbuilt-in,sometimesjustnamesofprograms
BourneShellCommandInterpreter
26
UserOperatingSystemInterface–GUI
• User-friendly desktop metaphor interface (an interface metaphoris a set of user interfacevisuals, actionsand procedures
that exploit specific knowledge that users already have of other domain)
– Usuallymouse,keyboard,andmonitor
– Iconsrepresentfiles,programs,actions,etc
– Variousmousebuttonsoverobjectsintheinterfacecausevariousactions(provideinformation,
options,executefunction,opendirectory(knownasafolder)
– InventedatXeroxPARC
• ManysystemsnowincludebothCLIandGUIinterfaces
– MicrosoftWindowsisGUIwithCLI“command”shell
– AppleMacOSXis“Aqua”GUIinterfacewithUNIXkernelunderneathandshellsavailable
– UnixandLinuxhaveCLIwithoptionalGUIinterfaces(CDE,KDE,GNOME)
UserOperatingSystemInterface–TouchscreenInterfaces
Touchscreendevicesrequirenewinterfaces
Mousenotpossibleornotdesired
Actions and selection based on touches or gestures Virtual
keyboard for text entry
Voicecommands.
27
The Mac OS X GUI
SystemCalls
o Systemcallsprovideaninterfacetotheservicesmadeavailablebyanoperatingsystem
o Tounderstandsystemcalls,firstoneneedstounderstandthedifferencebetween kernel mode and user mode
ofa CPU.Every modern operating system supports these two modes.
28
UserMode
• WhenCPUisinusermode,theprogramsdon'thavedirectaccesstomemoryandhardwareresources.
• Inusermode,ifanyprogramcrashes,onlythatparticularprogramishalted.
• Thatmeansthesystemwillbeinasafestateevenifaprograminusermodecrashes.
• Hence,mostprogramsinanOSruninusermode.
KernelMode
• WhenCPUisinkernelmode,thecodebeingexecutedcanaccessanymemoryaddressandany hardwareresource.
• Hencekernelmodeisaveryprivilegedandpowerfulmode.
• Ifaprogramcrashesinkernelmode,theentiresystemwillbehalted.
SystemCalls
• When a program in user mode requires access to RAMor a hardware resource, it must ask the kernel
toprovideaccesstothatresource.Thisisdoneviasomethingcalledasystemcall.
• When a program makes a system call, the mode of CPU is switched from user mode to kernel mode.
Thisiscalledacontextswitch.
• Thenthekernelprovidestheresourcewhichtheprogramrequested.Afterthat,anothercontextswitch
happenswhichresultsinchangeofmodefromkernelmodebacktousermode.
• Generally,systemcallsaremadebytheuserlevelprogramsinthefollowingsituations:
Creating,opening,closinganddeletingfilesinthefilesystem.
Creatingandmanagingnewprocesses.
Creatingaconnectioninthenetwork,sendingandreceivingpackets.
Requestingaccesstoahardwaredevice,likeamouseoraprinter.
• SoSystem call istheprogrammaticwayinwhichacomputerprogram requestsaservicefrom thekernel
oftheOperatingSystem.
29
• ProgramminginterfacetotheservicesprovidedbytheOS
• ThesecallsaregenerallyavailableasroutineswritteninCorC++
• Threemost commonAPIsareWin32API forWindows, POSIX APIforPOSIX-basedsystems(includingvirtuallyall
versionsof UNIX, Linux, andMacOSX), andJavaAPI fortheJavavirtual machine(JVM)
ExampleofSystemCalls
ExampleofStandardAPI
SystemCallImplementation
Typically,anumberassociatedwitheachsystemcall
30
– System-callinterfacemaintainsatableindexedaccordingtothesenumbers
• The system call interface invokesthe intended system call in OS kernel and returns status of the
systemcallandanyreturnvalues
• Thecallerneedknownothingabouthowthesystemcallisimplemented
– JustneedstoobeyAPIandunderstandwhatOSwilldoasaresultcall
– MostdetailsofOSinterfacehiddenfromprogrammerbyAPI
API–SystemCall–OSRelationship
SystemCallParameterPassing
• Often,moreinformationisrequiredthansimplyidentityofdesiredsystemcall
– ExacttypeandamountofinformationvaryaccordingtoOSandcall
• ThreegeneralmethodsusedtopassparameterstotheOS
– Simplest:passtheparametersinregisters
• Insomecases,maybemoreparametersthanregisters
– Parameters stored in a block,or table, in memory, and address of block passed as a parameter in a register
31
• ThisapproachtakenbyLinuxandSolaris
– Parameters placed, or pushed,onto the stack by theprogram and popped off the stack by the operating
system
Blockandstackmethodsdonotlimitthenumberorlengthofparametersbeingpassed
ParameterPassingviaTable
TypesofSystemCalls
Sixmajorcategoriessystemcallsareasfollows:
1.Processcontrol
– createprocess,terminateprocess
– end,abort
– load,execute
– getprocessattributes,setprocessattributes
– waitfortime
– waitevent,signalevent
– allocateandfreememory
– Dumpmemoryiferror
– Debuggerfordeterminingbugs,singlestepexecution
32
– Locksformanagingaccesstoshareddatabetweenprocesses
2. Filemanagement
– createfile,deletefile
– open,closefile
– read,write,reposition
– getandsetfileattributes
3. Devicemanagement
– requestdevice,releasedevice
– read,write,reposition
– getdeviceattributes,setdeviceattributes
– logicallyattachordetachdevices
4. Informationmaintenance
– gettimeordate,settimeordate
– getsystemdata,setsystemdata
– getandsetprocess,file,ordeviceattributes
5. Communications
– create,deletecommunicationconnection
– send,receivemessagesifmessagepassingmodeltohostnameorprocessname
• Fromclienttoserver
– Shared-memorymodelcreateandgainaccesstomemoryregions
– transferstatusinformation
– attachanddetachremotedevices
6. Protection
– Controlaccesstoresources
– Getandsetpermissions
– Allowanddenyuseraccess
33
ExamplesofWindowsandUnixSystemCalls
StandardCLibraryExample
• Cprograminvokingprintf()librarycall,whichcallswrite()systemcall
34
SystemPrograms
• System programsalso known as system utilities provide a convenient environment for program
developmentandexecution.Someofthemaresimplyuserinterfacestosystemcalls;othersare
considerablymorecomplex.Theycanbedividedinto:
– Filemanipulation:
– Statusinformation
– Filemodification
– Programminglanguagesupport
– Programloadingandexecution
– Communications
– Backgroundservices
– Applicationprograms
• Mostusers’viewoftheoperatingsystemisdefinedbysystemprograms,nottheactualsystemcalls
35
• Provideaconvenientenvironmentforprogramdevelopmentandexecution
– Someofthemaresimplyuserinterfacestosystemcalls;othersareconsiderablymorecomplex
• Filemanagement-Create,delete,copy,rename,print,dump,list,andgenerallymanipulatefilesand directories
• Statusinformation
– Othersprovidedetailedperformance,logging,anddebugginginformation
– Typically,theseprogramsformatandprinttheoutputtotheterminalorotheroutputdevices
– Somesystemsimplementaregistry-usedtostoreandretrieveconfigurationinformation
• Filemodification
– Texteditorstocreateandmodifyfiles
– Specialcommandstosearchcontentsoffilesorperformtransformationsofthetext
• Programming-languagesupport-Compilers,assemblers,debuggersandinterpreterssometimes provided
• Programloadingandexecution-Absoluteloaders,relocatableloaders,linkageeditors,andoverlay- loaders,
debugging systems for higher-level and machine language
• Communications - Provide the mechanism for creating virtual connections among processes, users, and computer
systems
– Allow users to send messages to one another’s screens, browse web pages, send electronic-mail
messages,loginremotely,transferfilesfromonemachinetoanother
• BackgroundServices
– Launchatboottime
• Someforsystemstartup,thenterminate
• Somefromsystemboottoshutdown
– Providefacilitieslikediskchecking,processscheduling,errorlogging,printing
– Runinusercontextnotkernelcontext
– Knownasservices,subsystems,daemons
• Applicationprograms
– Don’tpertaintosystem
36
– Runbyusers
– NottypicallyconsideredpartofOS
– Launchedbycommandline,mouseclick,fingerpoke
Operating-SystemDesignandImplementation
• DesignGoals
– Usergoals–operatingsystemshouldbeconvenienttouse,easytolearn,reliable,safe,andfast
– System goals– operating system should be easyto design, implement, andmaintain,aswell asflexible,
reliable, error-free, and efficient
• MechanismsandPolicies:
– Policiesdeterminewhatistobedone.
– Mechanismsdeterminehowitistobeimplemented.
• Implementation
– TraditionallyOSeswerewritteninassemblylanguage
Most modern OSes are written in C, or more recently, C++. Critical sections of code are still written inassembly language,
(orwritteninC,compiledtoassembly
OperatingSystemStructure
Requirements for operating systems can vary greatly depending on the planned scope and usage of the system. ( Single user /
multi-user, specialized system / general purpose, high/low security, performance needs, operating
environment,etc.).Thatmeansaffectedbychoiceofhardware,typeofsystem
• SotheInternalstructureofdifferentOperatingSystemscanvarywidely
• Startbydefininggoalsandspecifications
UsergoalsandSystemgoals
– Usergoals–operatingsystemshouldbeconvenienttouse,easytolearn,reliable,safe,andfast
– System goals – operating system should be easy to design, implement, and maintain, as well asflexible,
reliable, error-free, and efficient
Structure/Organization/LayoutofOperatingSystems:
OS components and its organization and its interactions is calledOperating Systemstructure. The following are the some of
the OS structures.
37
1. SimpleStructure--MS-DOS
• MS-DOS–writtentoprovidethemostfunctionalityintheleastspace
– Notdividedintomodules
– AlthoughMS-DOShassomestructure,itsinterfacesandlevelsoffunctionalityarenotwell separated
2. NonSimpleStructureorMonolithic--UNIX
Traditionally,systemssuchasUnixwerebuiltasamonolithickernel:
38
TheUNIXOSconsistsoftwoseparableparts
– Systemsprograms
– Thekernel
• Consistsofeverythingbelowthesystem-callinterfaceandabovethephysicalhardware
• Providesthefilesystem,CPUscheduling,memorymanagement,andotheroperating-
systemfunctions;alargenumberoffunctionsforonelevel
TraditionalUNIXSystemStructure
Beyondsimplebutnotfullylayered
3. LayeredApproach
39
• Theoperatingsystemisdividedintoanumberoflayers(levels),eachbuiltontopoflowerlayers.
• Thebottomlayer(layer0)isthehardware;thehighest(layerN)istheuserinterface.
• With modularity, layers are selected such that each uses functions (operations) and services of only lower- level
layers.
ThefirstdescriptionofthisapproachwasDijkstra’ssystem.
4. MicrokernelSystemStructure
• The basic idea behind micro kernels is to remove all non-essential services from the kernel, andimplement them
assystem applicationsinstead, therebymaking the kernel as small and efficient aspossible.
• Most microkernels provide basic process and memory management, and message passing between other services, and
not much more.
• Communicationtakesplacebetweenusermodulesusingmessagepassing
• Securityandprotectioncanbeenhanced,asmostservicesareperformedinusermode,notkernelmode.
• System expansion can also be easier, because it only involves adding more system applications, not
rebuildinganewkernel.
• Machwasthefirstandmostwidelyknownmicrokernel,andnowformsamajorcomponentofMacOSX.
40
• Windows NT was originally microkernel, but suffered from performance problems relative to Windows 95.NT 4.0
improved performance bymoving more services into the kernel, and now XP is back to being more monolithic.
• AnothermicrokernelexampleisQNX,areal-timeOSforembeddedsystems.
• Benefits:
– Easiertoextendamicrokernel
– Easiertoporttheoperatingsystemtonewarchitectures
– Morereliable(lesscodeisrunninginkernelmode)
– Moresecure
• Detriments:
– Performanceoverheadofuserspacetokernelspacecommunication
MicrokernelSystemStructure
messages messages
memory managment
Interprocess Communication CPU
scheduling kernel
mode
microkernel
hardware
5. Modularkernel
• Manymodernoperatingsystemsimplementloadablekernelmodules
– Usesobject-orientedapproach
– Eachcorecomponentisseparate
41
– Eachtalkstotheothersoverknowninterfaces
– Eachisloadableasneededwithinthekernel
• Overall,similartolayersbutwithmoreflexible
– Linux,Solaris,etc
SolarisModularApproach
HybridSystems
• Mostmodernoperatingsystemsareactuallynotonepuremodel
– Hybridcombinesmultipleapproachestoaddressperformance,security,usabilityneeds
– Linux and Solaris kernels in kernel address space,so monolithic,plus modular for dynamicloading of
functionality
ex:MacOSXStructure
– AppleMacOSXhybrid,layered,AquaUIplusCocoaprogrammingenvironment
– Below is kernel consisting of Mach microkernel andBSD Unix parts, plus I/O kit and dynamicallyloadable
modules (calledkernelextensions)
– The Mac OSX architecture relies on the Mach microkernelfor basic systemmanagementservices, and the
BSD kernel for additional services.
Applicationservicesanddynamicallyloadablemodules(kernelextensions)providetherestoftheOS functionality:
42
MacOSXStructure
graphicaluserinterface
Aqua
applicationenvironmentsandservices
kernel environment
BSD
Mach
iOS
• ApplemobileOSforiPhone,iPad
– CocoaTouchObjective-CAPIfordevelopingapps
– Mediaserviceslayerforgraphics,audio,video
– Coreservicesprovidescloudcomputing,databases
– Coreoperatingsystem,basedonMacOSXkernel
Android
• DevelopedbyOpenHandsetAlliance(mostlyGoogle)
43
– OpenSource
44
• SimilarstacktoIOS
• BasedonLinuxkernelbutmodified
– Providesprocess,memory,device-drivermanagement
– Addspowermanagement
• RuntimeenvironmentincludescoresetoflibrariesandDalvikvirtualmachine
– AppsdevelopedinJavaplusAndroidAPI
• Java class files compiled to Java bytecode then translated to executable than runs in Dalvik
VM
• Librariesincludeframeworksforwebbrowser(webkit),database(SQLite),multimedia,smallerlibc
Android Architecture
ApplicationFramework
Libraries Androidruntime
surface manager
media framework Dalvik virtualmachine
webkit libc
Operating-System Debugging
Debugging is the process of finding the problems in a computer system and solving them.
Therearemanydifferentwaysinwhichoperatingsystemsperformdebugging.Someofthese are:
Log Files
45
Thelogfilesrecordalltheeventsthatoccurinanoperatingsystem.Thisisdonebywritingall the messages in to
a log file. There are different types of log files. Some of these are given as follows:
Event Logs
These stores the records of all the events that occur in the execution of a system. This is done so that
the activities of all the events can be understood to diagnose problems.
Transaction Logs
The transaction logs store the changes to the data so that the system can recover from crashes and
other errors. These logs are readable by a human.
Message Logs
These logs store both the public and private messages between the users. They are mostly plain text
files, but in some cases they may be HTML files.
The core dump files contain the memory address space of a process that terminates unexpectedly. The
creation of the core dump is triggered in response to program crashes by the kernel. The core dump
files are used by the developers to find the program’s state at the time of its termination so that they
can find out why the termination occurred.
KernelMemoryDump
46
are stored in the kernel memory dump.
SmallMemoryDump
This memory dump contains the list of device drivers, stop code, process and thread information,
kernel stack etc.
TraceListings(DTrace)
Thetracelistingrecordinformationaboutaprogramexecutionusinglogging.Thisinformation is used by
programmers for debugging. System administrators and technical personnel can use the trace listings
to find the common problems with software using software monitoring tools.
Useanoperatingsystemprobetomonitorsystemresources,CPUusage,diskactivity, physical
memory use, and network traffic.Probes fire when codeis executed within a provider, capturing
state data and sending it to consumers of those probes
Example of following XEventsQueued system call move fromlibclibrary to kernel and back
DTracecodetorecordamountoftimeeachprocesswithUserID101isinrunningmode (on CPU)
in nanoseconds
47
Profiling
Thisisatypeofprogramanalysisthatmeasuresvariousparametersinaprogramsuch
asspaceandtimecomplexity,frequencyanddurationoffunctioncalls,usageofspecific
instructionsetc.Profilingisdonebymonitoringthesourcecodeoftherequiredsystem program using
a code profiler.
System Boot
The BIOS, operating system and hardware components of a computer system should all be working
correctly for it to boot. If any of these elements fail, it leads to a failed boot sequence.
The following diagram demonstrates the steps involved in a system boot process:
48
Here are the steps:
TheCPUinitializesitselfafterthepowerinthecomputerisfirstturnedon.Thisisdone by triggering a
series of clock ticks that are generated by the system clock.
Afterthis,theCPUlooksforthesystem’sROMBIOStoobtainthefirstinstructioninthe start-up
program. This first instruction is stored in the ROM BIOS and it instructs the
systemtorunPOST(PowerOnSelfTest)inamemoryaddressthatispredetermined.
POSTfirstcheckstheBIOSchipandthentheCMOSRAM.Ifthereisnobatteryfailure detected by
POST, then it continues to initialize the CPU.
POST also checks the hardware devices, secondary storage devices such as hard drives, ports
etc. And other hardware devices such as the mouse and keyboard. This is done to make sure
they are working properly.
After POST makes sure that all the components are working properly, then the BIOS finds an
operating system to load.
In most computer systems, the operating system loads from the C drive on to the hard drive.
The CMOS chip typically tells the BIOS where the operating system is found.
TheorderofthedifferentdrivesthatCMOSlooksatwhilefindingtheoperatingsystem
isknownasthebootsequence.ThissequencecanbechangedbychangingtheCMOS setup.
49
After finding the appropriate boot drive, the BIOS first finds the boot record which tells it to
find the beginning of the operating system.
After the initialization of the operating system, the BIOS copies the files in to the memory.
Then the operating system controls the boot process.
In the end, the operating system does a final inventory of the system memory and loads the
device drivers needed to control the peripheral devices.
The users can access the system applications to perform various tasks.
Without the system boot process, the computer users would have to download all the software
components, including the ones not frequently required. With the system boot, only those
softwarecomponentsneedtobedownloadedthatarelegitimatelyrequiredandallextraneous components are
not required. This process frees up a lot of space in the memory and consequently saves a lot of time.
50