OS Lab Manual
OS Lab Manual
Assignment No. 1
TostudyBasicLinuxCommandsandShellprogramming.
A. Study of Basic Linux Commands: echo, ls, read, cat, touch, test, loops, arithmetic
comparison,conditionalloops,grep,sedetc.
B. Write a programto implement anaddress book withoptions given below: a) Create
addressbook.b)Viewaddressbook.c)Insertarecord.d)Deletearecord.e)Modifya
record.f)Exit
OBJECTIVE:
Tostudy
1. BasicLinuxcommands
2. Shell script
THEORY:
LinuxCommands
The Linux command is a utility of the Linux operating system. All basic and advanced tasks
can be done by executing commands. The commands are executed on the Linux terminal.
The terminal is a command-line interface to interact withthe system, which is similar to the
commandprompt in the Windows OS. Commands in Linuxare case-sensitive
Basic Linux Commands
mkdir Command
The mkdir command is used to create anew directoryunder any directory
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Syntax:
mkdir <directory name>
rmdir Command
The rmdircommand is used to delete a directory.
Syntax:
rmdir <directoryname>
cd Command
The cd command isusedto change the current directory.
Syntax:
cd<directory name>
touchCommand
The touchcommand is used tocreate emptyfiles. We cancreate multiple empty
files byexecuting it once.
Syntax:
touch<file name>
touch<file1><file2>
catCommand
The cat command is a multi-purpose utilityin the Linux system. It canbe usedto
create a file, displaycontent of the file, copy the content of one file to another file,
and more.
Syntax:
cat [OPTION]... [FILE]..
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
To create a file, execute it as follows:
cat><file name>
// Enterfile content
Press"CTRL+ D" keys to save the file. Todisplaythe content of the file, execute it as
follows:
cat<file name>
rmCommand
The rmcommand is used toremove afile.
Syntax:
rm <file name>
ls Command
The ls command is usedto display alistof content of adirectory.
Syntax:
ls
catCommand
The cat command is also usedas afilter. To filtera file, it isused inside pipes.
Syntax:
cat<fileName> | cat ortac | cat ortac |
grepCommand
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
The grep is the most powerful and usedfilter in a Linuxsystem. The 'grep'stands for
"global regular expression print." It is useful for searching the content from a file.
Generally, it is used withthe pipe.
Syntax:
command| grep <searchWord>
sedcommand
The sed command is also known as stream editor. It is used to edit files using a
regular expression. It does not permanently edit files; instead, the edited content
remains onlyon display. It doesnot affect the actual file.
Syntax:
command| sed 's/<oldWord>/<newWord>/'
sortCommand
The sort command is usedto sort files in alphabeticalorder.
Syntax:
sort<file name>
calCommand
The calcommand is used todisplaythe current month's calendarwiththe current
date highlighted.
Syntax:
cal<
readcommand
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
The read command is used to read from a file descriptor. This command read up
the total number of bytes from the specified file descriptor into the buffer. If the
number or count is zero then this command may detect the errors. But on success,
it returns the number of bytes read. Zero indicates the end of the file. If some errors
found then it returns -1
Syntax:
read
echocommand
echo command in linux is used to display line of text/string that are passed as an
argument . This is a built in command that is mostly used in shell scripts and batch
files tooutput status text to the screenora file.
Syntax:
echo [option] [string]
testcommand
Test is used as part of the conditional execution of shell commands.test exits with
the status determined by EXPRESSION. Placing the EXPRESSION between square
brackets ([ and ]) is the same as testing the EXPRESSION with test. To see the exit
status at the command prompt, echo the value "$?" A value of 0 means the
expression evaluated as true, and a value of 1 means the expression evaluated as
false
Syntax:
test EXPRESSION
[ EXPRESSION ]
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Shell Script: Normally shells are interactive. It means shell accept command from you (via
keyboard)andexecutethem.Butifyouusecommandonebyone(sequenceof'n'numberof
commands), the you can store this sequence of command to text file and tell the shell to
execute this text file instead of entering the commands. This is known as shell script. Shell
Scriptisseriesofcommandwrittenin plain textfile.Thismanualismeantasabriefintroduction
tofeaturesfoundin Bash.
ExitStatus:
Bydefault inLinuxif particularcommand/shell scriptisexecuted,it returntwotypeofvalues
whichis usedtoseewhethercommandorshellscriptexecutedis successfulornot.
(1)Ifreturnvalueis zero(0),commandis successful.
(2)Ifreturnvalueisnonzero,commandisnotsuccessfulorsomesortoferrorexecuting
command/shell script.
Thisvalueis knownasExit Status.Buthowtofindoutexit statusofcommandorshell script?
Simple,todeterminethis exit Statusyoucanuse$?specialvariableofshell.
Fore.g.(This exampleassumesthatunknow1file doesnotexistonyourharddrive)
$rmunknow1file
Itwil showerrorasfollows
rm:cannotremove`unkowm1file':Nosuchfileordirectory
andafterthatif yougivecommand
$echo$?
it will printnonzerovaluetoindicateerror.
Userdefinedvariables(UDV)
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
TodefineUDVusefollowingsyntax
Syntax:
variablename=value
'value'isassignedtogiven'variablename'andValuemustbeonrightside=sign.
Example:
Todefinevariable callednhavingvalue10
$n=10
ToprintoraccessUDVusefollowingsyntax
Syntax:
$variablename
$n=10
Toprintcontainsofvariable'n'typecommandasfollows
$echo$n
AboutQuotes
Therearethreetypesofquotes
Quotes Name Meaning
" Doubl e "Doubl e Quotes"-Anythingenclo sein double quotesremoved
Quotes meaningofthatcharacters(except\and$).
' Single quotes 'Single quotes'-Enclosedinsingle quotesremainsunchanged.
` Backquote `Backquote`-Toexecutecommand
Example:
$echo"Todayis date"
Can'tprintmessagewithtoday's date.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
$echo"Todayis `date`".
RulesforNamingvariablename(BothUDVandSystemVariable)
(1)VariablenamemustbeginwithAlphanumeric characterorunderscorecharacter(_),
followedbyoneormoreAlphanumericcharacter.Fore.g.Validshellvariable areasfollows
HOME
SYSTEM_VERSION
(2)Don't putspacesoneithersideoftheequalsignwhenassigningvaluetovariable.Fore.g.In
followingvariable declarationtherewillbenoerror
$no=10
Buttherewil beproblemforanyofthefollowingvariable declaration:
$no=10
$no=10
$no=10
(3)Variablesarecase-sensitive,justlikefilenameinLinux.
(4)YoucandefineNULLvariable asfollows(NULLvariable is variable whichhasnovalueatthe
timeofdefinition)Fore.g.
$vech=
$vech=""
Trytoprintit's valuebyissuingfollowingcommand
$echo$vech
Nothingwillbeshownbecausevariable hasnovaluei.e.NULLvariable.
(5)Donotuse?,*etc,tonameyourvariablenames.
Shell Arithmetic
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Usetoperformarithmetic operations.
Syntax:
exprop1math-operatorop2
Examples:
$expr1+3
$expr2-1
$expr10/2
$expr20%3
$expr10\*3
$echo`expr6+3`
Note:
expr20%3-Remainderreadas20mod3andremainderis 2.
expr10\*3-Multiplicationuse\*andnot*sinceitswild card.
ThereadStatement
Usetogetinput(datafromuser)fromkeyboardandstore(data)tovariable.
Syntax:
readvariable1,variable2,...variableN
Followingscriptfirstaskuser,nameandthenwaitstoenternamefromtheuservia
keyboard.Thenuserentersnamefromkeyboard(aftergivingnameyouhavetopressENTER
key)andenterednamethroughkeyboardis stored(assigned)tovariable fname.
$visayH
#
#Scripttoreadyournamefromkey-board
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
#
echo"Yourfirstnameplease:"
readfname
echo"Hello$fname,Letsbefriend!"
VariablesinShell
Toprocessourdata/information, datamustbekept in computersRAMmemory.RAM
memoryis dividedintosmalllocations,andeachlocationhaduniquenumbercalledmemory
location/address,whichis usedtohold ourdata.Programmercangiveauniquenametothis
memorylocation/address calledmemoryvariable orvariable (Its anamedstorage location
thatmaytakedifferentvalues,butonly oneatatime).
InLinux(Shell),therearetwotypesofvariable:
(1)Systemvariables-CreatedandmaintainedbyLinuxitself.Thistypeofvariable definedin
CAPITALLETTERS.
(2)Userdefinedvariables(UDV)-Createdandmaintainedbyuser.Thistypeofvariable
definedinlowerletters.
Youcanseesystemvariablesbygivingcommandlike$set,someoftheimportantSystem
variablesare:
SystemVariable Meaning
BASH=/bin/bash Ourshell name
BASH_VERSION=1.14.7(1) Ourshell versionname
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
HOME=/home/vivek Ourhomedirectory
LOGNAME=students studentsOurloggingname
OSTYPE=Linux OurOstype
PATH=/usr/bin:/sbin:/bin:/usr/sbin Ourpathsettings
PWD=/home/students/Common Ourcurrentworkingdirectory
SHELL=/bin/bash Ourshell name
Youcanprintanyoftheabovevariablescontainsasfollows:
$echo$HOME
testcommandor[expr]
testcommandor[expr]isusedtoseeif anexpressionis true,andif it istrueit returnzero(0),
otherwisereturnsnonzeroforfalse.
Syntax:
testexpressionOR[expression]
Example:
Followingscriptdeterminewhethergivenargumentnumberis positive.
if test$1-gt0
then
echo"$1numberis positive"
fi
testor[expr]workswith
1.Integer(Numberwithoutdecimalpoint)
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
2.Filetypes
3.Characterstrings
ForMathematics,usefollowingoperatorin ShellScript
Operator
Normal
in Shell Meaning Butin Shell
Arithmetical
Script
-eq is equalto 5==6 if test5-eq6 if [5-eq6]
-ne is notequalto 5!=6 if test5-ne6 if [5-ne6]
-lt is lessthan 5<6 if test5-lt 6 if [5-lt6]
-le is lessthanorequalto 5<=6 if test5-le 6 if [5-le6]
-gt is greaterthan 5>6 if test5-gt6 if [5-gt6]
-ge is greaterthanorequalto 5>=6 if test5-ge6 if [5-ge6]
NOTE:==isequal, !=is notequal.
ForstringComparisonsuse
Operator Meaning
string1=string2 string1is equaltostring2
string1!=string2 string1is NOTequaltostring2
string1 string1is NOTNULLornotdefined
-nstring1 string1is NOTNULLanddoesexist
-zstring1 string1is NULLanddoesexist
Shell alsotestforfile anddirectorytypes
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Meaning
-sfile Nonemptyfile
IsFile existornormalfileandnota
-ffile
directory
-ddir IsDirectoryexistandnotafile
-wfile Iswriteable file
-rfile Isread-only file
-xfile Isfile is executable
LogicalOperators:
Logicaloperatorsareusedtocombinetwoormoreconditionatatime
Operator Meaning
!expression LogicalNOT
expression1 -a expression2 LogicalAND
expression1 -o expression2 LogicalOR
ifcondition
if conditionwhichisusedfordecisionmakingin shellscript,If givenconditionis truethen
command1is executed.
Syntax:
if condition
then
command1if conditionistrueorifexit status
ofconditionis0(zero)
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
…
…
fi
Conditionis definedas:
“Conditionis nothingbutcomparisonbetweentwovalues.”
Forcompressionyoucanusetestor[expr]statementsorevenexiststatuscanbealsoused.
LoopsinShellScripts
Bashsupports:
1)forloop
2)whileloop
while:
Thesyntaxofthewhileis:
while
done
Execute aslongas hasanexitstatusofzero.
for:
Thesyntaxoftheforis:
forvariable in list
do
done
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Each white space-separated word in list is assinged to variable in turn and commands
executeduntil listisexhausted.
ThecaseStatement
ThecasestatementisgoodalternativetoMultilevelif-then-else-fistatement.Itenableyou
to match several values against one variable. Its easier to read and write.
Syntax:
case $variable-name in
pattern1) command
...
..
command;;
pattern2) command
...
..
command;;
patternN) command
...
..
command;;
*) command
...
..
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
command;;
esac
The$variable-nameiscomparedagainstthepatternsuntil amatchis found.Theshell
thenexecutesall thestatementsuptothetwosemicolonsthatarenexttoeachother.The
default is *)anditsexecutedif nomatchis found.
Conclusion:Thusinshell scriptwecanwriteseriesofcommandsandexecute
asasingle program.
Answerthefollowingquestions.
1. Whataredifferenttypesofshell&differentiatethem.
2. Explain Exit statusofacommand.
3. Explain a)Userdefinevariables.
4. Systemvariables.
5. Whatismancommand?
6. Explain testcommand.
7. Explain howshell programgetexecuted.
8. Explain syntaxofif-else,for,while,case.
9. Explain useoffunctionsin shellandshowit practically.
10. Writeamenudrivenshellscripttoexecutedifferentcommandswithoptions.
Assignment No. 2
Processcontrolsystemcalls:ThedemonstrationofFORK,EXECVEandWAITsystemcalls
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
alongwithzombie andorphanstates.
A. Implement the C programin whichmain program accepts the integers to be sorted.
Main program uses the FORK system call to create a new process called a child
process.Parentprocesssortstheintegersusingsortingalgorithmandwaitsforchild
processusingWAITsystemcall tosorttheintegersusinganysortingalgorithm.Also,
demonstrate zombie and orphan states.Write a program to implement an address
bookwithoptionsgivenbelow:a)Createaddressbook.b)Viewaddressbook.c)Insert
arecord.d)Deletearecord.e)Modifyarecord.f)Exit
B. ImplementtheCprograminwhichmainprogramacceptsanarray.Main programuses
theFORKsystemcall tocreateanew processcalledachild process.Parentprocess
sortsanarrayandpassesthesortedarraytochild processthroughthecommandline
argumentsofEXECVEsystemcall. Thechild processusesEXECVEsystemcall toload
newprogramthatdisplayarrayin reverseorder.
OBJECTIVE:
Tostudy
Processcontrol
Zombie andorphanprocesses
Systemcalls:fork,execve,wait
THEORY:
Process
Aprocessis thebasicactiveentityin mostoperating-systemmodels.Aprocessisaprogramin
executionin memoryor in other words, aninstance of a programin memory. Anyprogram
executed creates a process. A program can be a command, a shell script, or any binary
executable oranyapplication.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
ProcessIDs
EachprocessinaLinuxsystemis identifiedbyitsunique ,sometimesreferredtoas
.ProcessIDsare16-bitnumbersthatareassignedsequential ybyLinuxasnewprocesses
arecreated.
WhenreferringtoprocessIDsin aC orC++program,alwaysuse the pid_ttypedef,whichis
definedin<sys/types.h>.AprogramcanobtaintheprocessIDoftheprocessit’ srunningin
withthe getpid() system call, and it can obtain the process ID of its parent process withthe
getppid()systemcall.
CreatingProcess
Twocommontechniquesareusedforcreatinganewprocess.
1. usingsystem()function
2. usingfork()systemcalls
1.system()function
The systemfunctionin the standardClibraryprovidesaneasywaytoexecute acommand
fromwithin aprogram,muchasifthe commandhadbeentypedintoashell.Infact,system
createsasubprocessrunningthestandardBourneshell(/bin/sh)andhandsthecommandto
thatshell forexecution.
The systemfunctionreturnsthe exit statusoftheshell command. Ifthe shell itself cannot be
run,systemreturns127;ifanothererroroccurs,systemreturns– 1.
2.forksystemcall
Aprocesscancreateanewprocessbycallingfork.Thecallingprocessbecomestheparent,
andthecreatedprocessis calledthechild.The fork functioncopiestheparent'smemoryimage
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
sothatthenewprocessreceivesacopyoftheaddressspaceoftheparent.Bothprocesses
continue at the instruction after the fork statement (executing in their respective memory
images).
Synopsis
#include<unistd.h>
pid_tfork(void);
The forkfunctionreturns0tothe childandreturnsthechild's processID totheparent.When
forkfails,it returns– 1.
WaitFunction
Whenaprocesscreatesachild,bothparentandchild proceedwithexecutionfromthepointof
thefork.Theparentcanexecute wait toblockuntil thechild finishes.Thewait functioncauses
the caller to suspend execution until a child's status becomes available or until the caller
receivesasignal.
Synopsis
#include<sys/wait.h>
pid_twait(int*status);
Ifwaitreturnsbecausethestatusofachild isreported,thesefunctionsreturntheprocessID of
thatchild.Ifanerroroccurs,thesefunctionsreturn– 1.
Example:
pid_tchildpid;
childpid =wait(NULL);
if (childpid !=-1)
printf("Waitedforchild withpid %ld\n",childpid);
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Statusvalues
The status argument of wait is a pointerto aninteger variable. If it is not NULL, this function
storesthe returnstatusofthe child inthislocation. The child returns itsstatusbycalling exit,
_exit orreturnfrommain.
AzeroreturnvalueindicatesEXIT_SUCCESS;anyothervalueindicatesEXIT_FAILURE.
POSIX specifies sixmacrosfortestingthe child's returnstatus. Eachtakesthe status value
returnedbyachild towaitasaparameter.Followingarethetwosuchmacros:
Synopsis
#include<sys/wait.h>
WIFEXITED(intstat_val)
WEXITSTATUS(intstat_val)
Execsystemcall
Usedfornewprogramexecutionwithin theexistingprocess.Theforkfunctioncreatesacopy
ofthecallingprocess,butmanyapplicationsrequirethechild processtoexecutecodethatis
differentfromthatoftheparent.Theexecfamily offunctionsprovidesafacilityforoverlaying
the process image of the calling process with a new image. The traditional way to use the
fork– execcombinationisforthe child toexecute (withanexecfunction) the newprogram
while the parent continues to execute the original code. The execsystemcallisusedafter a
fork system call by one of the two processes to replace the memory space with a new
program. The exec system call loads a binary file into memory (destroying image of the
programcontainingtheexecsystemcall) andgotheir separateways.Within theexecfamily,
therearefunctionsthatvaryslightly in their capabilities.
Synopsis
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
#include<unistd.h>
externchar**environ;
Execfamily
1. intexecl(constchar*path,constchar*arg0,.../*,char*(0)*/);
2. intexecle(constchar*path,constchar*arg0,.../*,char*(0),char*constenvp[]*/);
3. intexeclp(constchar*file,constchar*arg0,.../*,char*(0)*/);
4. intexecv(constchar*path,char*constargv[]);
5. intexecve(constchar*path,char*constargv[],char*constenvp[]);
6. intexecvp(constchar*file,char*constargv[]);
1.Execl()andexeclp():
execl()
Itpermitsustopassalistofcommandlineargumentstotheprogramtobeexecuted.
The listofargumentsisterminatedbyNULL.
e.g. execl("/bin/ls","ls","-l",NULL);
execlp()
Itdoessamejobexceptthatitwil useenvironmentvariablePATHtodeterminewhich
executable toprocess.Thus,afully qualifiedpathnamewould nothavetobeused. It
canalsotakethefullyqualifiednameasit alsoresolvesexplicitly.
e.g. execlp("ls","ls","-l",NULL);
2.Execv()andexecvp()
execv()
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Itdoessamejobasexecl()exceptthatcommandlineargumentscanbepassedtoit in
theformofanarrayofpointerstostring.
e.g. char*argv[]=("ls","-l",NULL);
execv("/bin/ls",argv);
execvp()
Itdoessamejobexpectthatitwil useenvironmentvariablePATHtodeterminewhich
executable toprocess.Thusafully qualifiedpathnamewouldnothavetobeused.
e.g. execvp("ls",argv);
3.execve()
Itexecutestheprogrampointedtobyfilename.
intexecve(constchar*filename,char*constargv[],char*constenvp[]);
Filenamemustbeeitherabinaryexecutable,orascriptstartingwithalineoftheform:
argvisanarrayofargumentstringspassedtothenewprogram.Byconvention,thefirst
of these stringsshouldcontainthe filename associatedwiththe file being executed.
envpisanarrayofstrings,conventionally oftheformkey=value,whicharepassedas
environmenttothenewprogram.BothargvandenvpmustbeterminatedbyaNULL
pointer. The argument vector and environment can be accessed by the called
program'smainfunction,whenitis definedas:
intmain(intargc,char*argv[],char*envp[])]
execve()doesnot returnonsuccess,andthe text, data,bss,andstackofthecalling
processareoverwrittenbythatoftheprogramloaded.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Allexecfunctionsreturn– 1if unsuccessful. Incaseofsuccessthesefunctionsneverreturnto
thecallingfunction.
ProcessTermination
Normally, a process terminates in one of two ways. Either the executing program calls the
exitfunction, or the program’ s main functionreturns. Each process has an exit code:
anumberthattheprocessreturnstoitsparent.Theexitcodeis theargumentpassedtotheexit
function,orthevaluereturnedfrommain.
ZombieProcesses
Ifachild processterminateswhile itsparentiscallingawaitfunction,thechild processvanishes
and its termination status is passed to its parent via the wait call. But what happens, when a
child processterminatesandtheparentis notcallingwait?Doesit simply vanish?No,because
theninformationaboutitstermination—suchaswhetherit exitednormally and, if so,whatits
exit statusis—would belost.Instead,whenachild processterminates,it becomesazombie
process.
A is aprocess thathasterminatedbuthas notbeencleanedupyet. Itis the
responsibilityoftheparentprocesstocleanupitszombie children.Thewaitfunctionsdothis,
too,soit’ snotnecessarytotrackwhetheryourchild processisstillexecutingbeforewaiting
for it. Suppose, for instance, that a program forks a child process, performs some other
computations, and then calls wait. If the child process has not terminated at that point, the
parent process wil block in the wait call until the child process finishes. If the child process
finishesbeforetheparentprocesscalls wait,thechild processbecomesazombie.Whenthe
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
parent process calls wait, the zombie child’ s termination status is extracted, the child
processis deleted,andthewait callreturnsimmediately.
OrphanProcess
Orphan process is the process whose parent process is dead. That is, parent process is
terminated,kil edorexitedbutthechild processisstillalive.
InLinux/Unixlikeoperatingsystems,assoonasparentsofanyprocessaredead,re-parenting
occurs, automatically. Re-parenting means orphaned process is immediately adopted by
specialprocess. Thingtonoticehereisthatevenafterre-parenting,theprocessstillremains
Orphanastheparentwhichcreatedtheprocessis dead.
Aprocesscanbeorphanedeitherintentionally orunintentionally.Sometimesaparentprocess
exits/terminates or crashes leaving the child process still running, and then they become
orphans. Also, a process canbe intentionallyorphaned just to keep it running. Forexample
whenyouneedtorunajobin thebackgroundwhichneedanymanualinterventionandgoingto
takelongtime,thenyoudetachitfromusersessionandleaveitthere.Sameway,whenyou
need to run a process in the background for infinite time, you need to do the same thing.
Processesrunninginthebackgroundlikethis areknownasdaemonprocess.
FindinganOrphanProcess
ItisveryeasytospotaOrphanprocess.Orphanprocessis auserprocess,whichis havinginit
process (process id 1) as parent. You can use this command in linux to find the orphan
processes.
#ps-elf |head-1;ps-elf |awk'{if ($5==1&&$3!="root"){print$0}}'|head
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
This wil show you all the orphan processes running in your system. The output from this
command confirms that they are orphan processes but does not mean that they are all
useless.
KillinganOrphanProcess
As orphan processes waste server resources, it is not advised to have lots of orphan
processesrunningintothesystem.Tokil aorphanprocessis sameaskillinganormalprocess.
#kil -15<PID>
Ifthatdoesnotworkthensimplyuse
#kil -9<PID>
DaemonProcess
Aprocessrunsinthebackground,ratherthanunderthedirectcontrolofauser.Theyare
usuallyinitiatedasbackgroundprocesses.
vfork
Itis alternativeoffork.Createsanewprocesswhenexecanewprogram.
Comparisonwithfork
1. Createsnewprocesswithoutfully copyingtheaddressspaceoftheparent.
2. vforkguaranteesthatthechild runsfirst,until thechild calls execorexit.
0. Whenchild callseitherofthesetwofunctions(exit,exec),theparentresumes.
Input
1. Anintegerarraywithspecifiedsize.
2. Anintegerarraywithspecifiedsizeandnumbertosearch.
Output
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
1. Sortedarray.
2. Statusofnumbertobesearched.
FAQS
IsOrphanprocessdifferentfromaZombie process?
AreOrphanprocessesharmfulforsystem?
Isit badtohaveZombie processesonyoursystem?
HowtofindanOrphanProcess?
HowtofindaZombie Process?
Whatiscommonshareddatabetweenparentandchild process?
WhatarethecontentsofProcessControlBlock?
PracticeAssignments
Example1
PrintingtheProcessID
#include<stdio.h>
#include<unistd.h>
intmain()
{
printf( “TheprocessIDis%d\n” ,(int)getpid());
printf( “TheparentprocessIDis %d\n” ,(int)getppid());
return0;
}
Example2
Usingthesystemcall
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
#include<stdlib.h>
intmain()
{
intreturn_value;
return_value=system( “ls– l/” );
returnreturn_value;
}
Example3
Usingforktoduplicateaprogram’ sprocess
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
intmain()
{
pid_tchild_pid;
printf( “ThemainprogramprocessIDis %d\n” ,(int)getpid());
child_pid=fork();
if(child_pid!=0)
{
printf( “Thisis theparentprocessID,withid%d\n” ,(int)getpid());
printf( “Thechild processIDis%d\n” ,(int)child_pid);
}
else
printf( “Thisis thechildprocessID,withid %d\n” ,(int)getpid());
return0;
}
Example4
Determiningtheexitstatusofachild
#include<stdio.h>#include<sys/types.h>#include<sys/wait.h>
void show_return_status(void)
{
pid_tchildpid;
intstatus;
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
childpid =wait(&status);if (childpid ==-1)
perror("Failedtowait forchild");
elseif(WIFEXITED(status))
printf("Child %ld terminatedwithreturnstatus%d\n",(long)childpid,
WEXITSTATUS(status));
}
Example5
Aprogramthatcreatesachildprocesstorunls-l
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
intmain(void)
{
pid_tchildpid;
childpid =fork();
if (childpid==-1){
perror("Failedtofork");
return1;
}
if (childpid==0){
/*child code*/
execl("/bin/ls","ls","-l",NULL);
perror("Childfailedtoexecls");return1;
}
if (childpid!=wait(NULL)){
/*parentcode*/
perror("Parentfailedtowait duetosignalorerror");return1;
}
return0;
}
Example6
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Makingazombieprocess
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
intmain()
{
pid_tchild_pid;
//createachildprocess
child_pid=fork();
if(child_pid>0) {
//This is aparentprocess.Sleepforaminute
sleep(60)
}
else
{
//This is achildprocess.Exitimmediately.
exit(0);
}
return0;
}
Example7
Demonstrationofforksystemcall
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
intmain()
{
pid_tpid;
char*msg;
intn;
printf( “Programstarts\n” );
pid=fork();
switch(pid)
{
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
case-1:
printf( “Forkerror\n” );
exit(-1);
case0:
msg=” Thisis thechildprocess” ;
n=5;
break;
default:
msg=” Thisis theparentprocess” ;
n=3;
break;
}
while(n>0)
{
puts(msg);
sleep(1);
n--;
}
return0;
}
Example8
Demoofmulti-processapplicationusingfork()systemcall
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#defineSIZE1024
void do_child_proc(intpfd[2]);
void do_parent_proc(intpfd[2]);
intmain()
{
intpfd[2];
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
intret_val,nread;
pid_tpid;
ret_val=pipe(pfd);
if(ret_val==-1)
{
perror( “pipeerror\n” );
exit(ret_val);
}
pid=fork();
switch(pid)
{
case-1:
printf( “Forkerror\n” );
exit(pid);
case0:
do_child_proc(pfd);
exit(0);
default:
do_parent_proc(pfd);
exit(pid);
}
wait(NULL);
return0;
}
void do_child_proc(intpfd[2])
{
intnread;
char*buf=NULL;
printf( “5\n” );
close(pfd[1]);
while(nread=(read(pfd[0],buf,size))!=0)
printf( “Child Read=%s\n” ,buf);
close(pfd[0]);
exit(0);
}
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
void do_parent_proc(intpfd[2])
{
charch;
char*buf=NULL;
close(pfd[0]);
while(ch=getchar()!=’ \n’ ) {
printf( “7\n” );
*buf=ch;
buff+;
}
*buf=’ \0’ ;
write(pfd[1],buf,strlen(buf)+1);
close(pfd[1]);
}
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
AssignmentNo. 3
Implementthe CprogramforCPUSchedulingAlgorithms:ShortestJobFirst(Preemptive)
andRoundRobin withdifferentarrivaltime.
OBJECTIVE:
Tostudy
• PreemptiveandNon-PreemptiveCPUscheduling
• ApplicationanduseofCPUschedulingAlgorithm
THEORY:
ShortestJobFirst(Preemptive)
WhatisShortestJobFirst?
Thisis anapproachwhichconsidersthenextCPUburst.EachprocesspossessitsnextCPU
burst.WhenCPUis available,theprocesshavingthesmallestnextCPUburstis allocatedCPU.
ItmayhappenthattwoormoreprocesseshavethesamenextCPUburst.Thenwhichprocess
toallocatewill bedecidedasperFCFSscheduling.
Shortest job first(SJF) is a scheduling algorithm, that is used to schedule processes in an
operatingsystem.It is averyimportanttopic in Schedulingwhencomparedtoround-robinand
FCFSScheduling.
TherearetwotypesofSJF
Pre-emptiveSJF
Non-PreemptiveSJF
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Thesealgorithmsschedule processesin theorderin whichtheshortestjobis donefirst.It hasa
minimumaveragewaitingtime.
Thereare3factorstoconsiderwhile solvingSJF,theyare
1. BURSTTime
2. Averagewaitingtime
3. Averageturnaroundtime
ShortestRemainingTimeFirst(SRTF)scheduling:
In the Shortest Remaining Time First (SRTF) scheduling algorithm, the process with the
smallestamountoftimeremaininguntilcompletionis selectedtoexecute.Sincethecurrently
executing process is the one with the shortest amount of time remaining by definition, and
since that time shouldonlyreduce as executionprogresses, processes will always rununtil
theycompleteoranewprocessis addedthatrequiresasmalleramountoftime.
ImplementationPoints:
1-Traverseuntilall processgetscompletely executed.
a)Findprocesswithminimumremainingtimeateverysingle timelap.
b)Reduceitstimeby1.
c)Checkif itsremainingtimebecomes0
d)Incrementthecounterofprocesscompletion.
e)Completiontimeofcurrentprocess=current_time+1;
e)Calculatewaitingtimeforeachcompletedprocess.
wt[i]=Completiontime– arrival_time_burst_time
f)Incrementtimelapbyone.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
2-Findturnaroundtime(waiting_time+burst_time).
KeyDifferencesBetweenPreemptiveandNon-PreemptiveScheduling:
1. Inpreemptivescheduling,theCPUisallocatedtotheprocessesforalimitedtimewhereas,
in Non-preemptive scheduling, the CPU is allocated to the process till it terminates or
switchestothewaitingstate.
2. Theexecutingprocessin preemptiveschedulingis interruptedin themiddle ofexecution
when higher priority one comes whereas, the executing process in non-preemptive
schedulingis notinterruptedin themiddle ofexecutionandwaitstil itsexecution.
3. InPreemptiveScheduling,thereis theoverheadofswitchingtheprocessfromtheready
statetorunningstate,vise-verseandmaintainingthereadyqueue.Whereasin thecaseof
non-preemptiveschedulinghasnooverheadofswitchingtheprocessfromrunningstate
toreadystate.
4. Inpreemptivescheduling,if ahigh-priorityprocessfrequently arrivesin thereadyqueue
thenthe processwithlow priorityhastowaitforalong,andit mayhave tostarve. ,inthe
non-preemptive scheduling,if CPUis allocatedtotheprocesshavingalargerbursttime
thentheprocesseswithsmall bursttimemayhavetostarve.
5. Preemptive scheduling attains flexibility byallowingthe critical processes toaccess the
CPUas theyarrive intothe readyqueue, nomatterwhat processis executing currently.
Non-preemptive scheduling is called rigid as even if a critical process enters the ready
queuetheprocessrunningCPUisnotdisturbed.
6. PreemptiveSchedulinghastomaintain theintegrityofshareddatathat’ swhyitis cost
associativewhichisnotthecasewithNon-preemptiveScheduling.
ShortestJobFirstAdvantagesandDisadvantages:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Advantages
Thisalgorithmissimpletoimplement.
priorityconsideration.
ItprovidesgoodCPUutilizationthanFCFS(FirstComeFirstSearch).
waitingtimeandturnaroundthetimeofthesystemascomparedtoFCFS.
Disadvantages
Waitingtimeofsomeprocessesstillhighduetothelongbursttimeoftheprocesses,in
caseofnon-preemptivescheduling.
In the case of non-preemptive scheduling, it may act as a uni-processing operating
system.
Inthecaseofpreemptivescheduling,contextswitchis required.
Andinpreemptivescheduling,turnaroundtimemaygetincreased.
PreemptiveSJFExample:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Code:
#include<stdio.h>
intmain()
{
intarrival_time[10],burst_time[10],temp[10];
inti, smallest,count=0,time,limit;
double wait_time=0,turnaround_time=0,end;
floataverage_waiting_time,average_turnaround_time;
printf("nEntertheTotalNumberofProcesses:t");
scanf("%d",&limit);
printf("nEnterDetails of%dProcessesn",limit);
for(i=0;i<limit;i++)
{
printf("nEnterArrivalTime:t");
scanf("%d",&arrival_time[i]);
printf("EnterBurstTime:t");
scanf("%d",&burst_time[i]);
temp[i]=burst_time[i];
}
burst_time[9]=9999;
for(time=0;count!=limit;time++)
{
smallest=9;
for(i=0;i<limit;i++)
{
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
if(arrival_time[i] <=time&&burst_time[i] <burst_time[smallest]&&burst_time[i]>0)
{
smallest=i;
}
}
burst_time[smallest]--;
if(burst_time[smallest]==0)
{
count++;
end=time+1;
wait_time=wait_time+end-arrival_time[smallest]-temp[smallest];
turnaround_time=turnaround_time+end-arrival_time[smallest];
}
}
average_waiting_time=wait_time/limit;
average_turnaround_time=turnaround_time/limit;
printf("nnAverageWaitingTime:t%lfn",average_waiting_time);
printf("AverageTurnaroundTime:t%lfn",average_turnaround_time);
return0;
}
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Output
RoundRobinwithdifferentarrivaltime
RoundRobinScheduling
Thenameofthis algorithmcomesfromtheround-robinprinciple,whereeachperson
getsanequalshareofsomethingin turns.
Eachprocessis assignedafixedtimeslotinacyclic way.TimeQuantum
InRound-robinscheduling,eachreadytaskrunsturnbyturnonlyinacyclic queuefora
limitedtimeslice.
Thisalgorithmalsooffersstarvationfreeexecutionofprocesses.
CharacteristicsofRoundRobin
Roundrobinisapre-emptivealgorithm
The CPU is shifted to the next process after fixed interval time, which is called time
quantum/timeslice.
Theprocessthatis preemptedis addedtotheendofthequeue.
Roundrobinisahybridmodelwhichis clock-driven
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Time slice should beminimum,whichisassignedforaspecific taskthatneeds tobe
processed.However,it maydifferOStoOS.
Itis arealtimealgorithmwhichrespondstotheeventwithin aspecific timelimit.
Roundrobinisoneoftheoldest,fairest,andeasiestalgorithm.
Widelyusedschedulingmethodin traditionalOS.
AdvantagesofRoundRobin
Itdoesnotfaceanystarvationissuesorconvoyeffect.
Eachprocessgetsequalprioritytothefair allocationofCPU.
Itdeals withallprocesswithoutanypriority.
Itis easytoimplementtheCPUSchedulingalgorithm.
Eachnewprocessisaddedtotheendofthereadyqueueasthenextprocess'sarrival
timeis reached.
Eachprocessis executedin circularorderthatsharesafixedtimeslotorquantum.
rescheduleafteragivenquantumperiod.
This scheduling method does not depend upon burst time. That's why it is easily
implementable onthesystem.
DisadvantagesofRoundRobin
If the time quantum is lower, it takes more time on context switching between the
processes.
Itdoesnotprovideanyspecialprioritytoexecutethemostimportantprocess.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Thewaitingtimeofalargeprocessishigherduetotheshorttimeslot.
Theperformanceofthealgorithmdependsonthetimequantum.
Theresponsetimeoftheprocessishigherduetolargeslicestotimequantum.
Getting a correct time slot or quantum is quite difficult for all processes in the
round-robin algorithm.
ExampleofRoundRobin#1
ProcessQueue BurstTime
P1 4
P2 3
P3 5
QueueRepresentationbasedonburstontime
NowTimeSlice=2
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Output:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Assignment No. 4
ThreadSynchronization
A. Thread synchronization using counting semaphores. Application to demonstrate:
producer-consumerproblemwithcountingsemaphoresandmutex.
B. Thread synchronization and mutual exclusion using mutex. Application to
demonstrate:Reader-Writerproblemwithreaderpriority.
OBJECTIVE:
Tostudy
• Semaphores
• Mutex
• Producer-ConsumerProblem
• Reader-Writerproblem
THEORY:
Semaphores:
Semaphore is an integer value used for signaling among processes. Only three operations
may be performed on a semaphore, all of which are atomic: initialize, decrement, and
increment.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
The decrement operation may result in the blocking of a process, and the increment
operationmayresult in the unblocking of a process. It is knownas a counting semaphore or
a generalsemaphore. Semaphores are the OS tools for synchronization.
Two types:
1. Binary Semaphore.
2. Counting Semaphore
Binary semaphore
Semaphores, which are restricted to the values 0 and 1 (or locked/unlocked, unavailable /
available), are called binary semaphores and are used toimplementlocks.
It is a means of suspending active processes, which are laterto be reactivated at such time
conditions are right for it to continue. A binary semaphore is a pointer which when held
by a process grants them exclusive use to their critical section. It is a (sort of) integer
variable which can take the values 0 or 1 and be operated upon only by two commands
termed in Englishwait and signal.
Counting semaphore
Semaphores which allow an arbitrary resource count are called counting
semaphores.
A counting semaphore comprises:
An integer variable, initialized to a value K (K>=0). During operation it can assume
any value<= K, a pointer to a process queue. The queue will hold the PCBs of all
those processes, waiting to enter their critical sections. The queue is implemented
as a FCFS, so that the waiting processesare served in aFCFS order.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Decrement (semWait)
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Value of semaphore
Positive
TheProducer/ConsumerProblem
There are one or more producers generating some type of data (records, characters) and
placing these in a buffer. There is a single consumer that is taking items out of the buffer
one at a time. The system is to be constrained to prevent the overlap of buffer operations.
That is, only one agent (producer or consumer) may access the buffer at any one time.
The problem is tomake sure that the producer won’ t trytoadd datainto the bufferifit’ s
full and that the consumer won’ t try to remove data from an empty buffer. To begin, let
us assume that the buffer is infinite and consists of a linear array of elements. In abstract
terms, we can define the producerand consumer functions as follows:
Figure illustrates the structure of buffer b. The producer can generate items and store
them in the buffer at its own pace. Each time, an index (in) into the buffer is incremented.
The consumerproceeds in a similar fashion but must make sure that it does not attempt to
readfromanemptybuffer. Hence, the
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Figure: Infinitebufferforproducer/consumerproblem
Solutionforboundedbufferusingcountingsemaphore
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
TheReaderWriterProblem.6READERS/WRITERSPROBLEM
Indealingwiththe designof synchronizationand concurrencymechanisms, it isuseful to be
able to relate the problem at hand to known problems and to be ableto test any solution in
terms of its ability to solve these known problems. The readers/writers problem is defined
as follows: There is a data area sharedamong a number of processes. The data area could
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
be a file, a block of main memory,or even a bank of processor registers. There are a
number of processes thatonly read the data area (readers) and a number that onlywrite to
the data area (writers). The conditions that must be satisfiedare as follows:
1. Any number of readers maysimultaneously read the file.
2. Only one writerat atime may write to the file.
3. If a writeriswriting to the file, noreader mayread it.
Thus, readers are processes that are not required to exclude one another andwriters are
processes that are required toexclude allother processes, readers andwritersalike.
In the readers/writers problem readers do not also write to the data area, nor do
writersread the data areawhile writing.
For example, suppose that the shared area is a library catalog.Ordinary users of the library
read the catalog to locate a book. One or more librariansare able to update the catalog. In
the general solution, every access to thecatalog would be treated as a critical section, and
users would be forced to readthe catalog one at a time. This would clearly impose
intolerable delays. At thesame time, it is important to prevent writers from interfering with
each other andit is also required to prevent reading while writing is in progress to prevent
the access
of inconsistentinformation.
ReadersHavePriority
Figure is a solution using semaphores, showing one instance each of a readerand a writer;
the solution does not change for multiple readers and writers.The writer process is simple.
The semaphore wsem is used to enforce mutualexclusion. As long as one writer is
accessing the shared data area, no other writersand no readers may access it. The reader
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
process also makes use of wsem toenforce mutual exclusion. However, to allow multiple
readers, we require that,when there are no readers reading, the first reader that attempts
to read shouldwait on wsem. When there is already at least one reader reading,
subsequentreaders need not wait before entering. The global variable readcount is used
tokeep track of the number of readers, and the semaphore x is used to assure
thatreadcount is updatedproperly.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
POSIXSemaphores
POSIX semaphoresallowprocessesandthreadstosynchronizetheir actions.Asemaphoreis
anintegerwhosevalueis neverallowedtofall belowzero. Twooperationscanbeperformed
onsemaphores:incrementthesemaphore valuebyone(sem_post(3));anddecrementthe
semaphorevaluebyone(sem_wait(3)). Ifthevalueofasemaphoreis currentlyzero,thena
sem_wait(3)operationwill blockuntilthevaluebecomesgreaterthanzero.
Semaphorefunctions:
1. sem_init()
It initializes the unnamed semaphore at the address pointed to by sem. The value
argumentspecifiestheinitialvalueforthesemaphore.
intsem_init(sem_t*sem,intpshared,unsignedintvalue);
2. sem_wait()
It decrements (locks) the semaphore pointed to by sem. If the semaphore's value is
greaterthanzero,thenthedecrementproceeds,andthefunctionreturns,immediately. If
thesemaphorecurrentlyhasthevaluezero,thenthecall blocksuntil itbecomespossibleto
performthedecrement.
intsem_wait(sem_t*sem);
3. sem_post()
It increments (unlocks) the semaphore pointed to by sem. If the semaphore's value
consequentlybecomes greaterthanzero, then another process orthread blocked in a
sem_wait(3)call willbewokenupandproceedtolockthesemaphore.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
intsem_post(sem_t*sem);
1. sem_unlink
Itremovesthenamedsemaphorereferredtobyname. Thesemaphorenameis removed
immediately. The semaphore is destroyed once all other processes that have the
semaphoreopencloseit.
intsem_unlink(constchar*name)
Alltheabovefunctionsreturns
0: Success
-1:Error
Mutex
Mutexesare a methodusedto be sure two threads, includingthe parent thread, donot
attempttoaccesssharedresourceatthesametime.Amutexlockallowsonly onethread
toenterthepartthat's lockedandthelockis notsharedwithanyotherprocesses.
1. pthread_mutex_init()
Thefunctionshall initializethemutexreferencedbymutexwithattributesspecifiedbyattr.
Ifattris NULL,thedefault mutexattributesareused;theeffectshallbethesameaspassing
theaddressofadefault mutexattributesobject.Uponsuccessfulinitialization,thestateof
themutexbecomesinitializedandunlocked.
intpthread_mutex_init(pthread_mutex_t*restrictmutex,cons
pthread_mutexattr_t *restrictattr);
2. pthread_mutex_lock()
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Themutexobjectreferencedbymutexshall belockedbycallingpthread_mutex_lock().If
themutexis alreadylocked,thecallingthreadshall blockuntilthemutexbecomesavailable.
Thisoperationshall returnwiththemutexobjectreferencedbymutexin thelockedstate
withthecallingthreadasitsowner.
intpthread_mutex_lock(pthread_mutex_t*mutex);
3. pthread_mutex_unlock()
Thefunctionshall releasethemutexobjectreferencedbymutex.Themannerin whicha
mutex is released is dependent upon the mutex's type attribute. If there are threads
blockedonthemutexobjectreferencedbymutexwhenpthread_mutex_unlock()is called,
resulting in the mutex becoming available, the scheduling policy shall determine which
threadshallacquirethemutex.
intpthread_mutex_unlock(pthread_mutex_t*mutex);
4. pthread_mutex_destroy()
The function shall destroy the mutex object referenced by mutex; the mutex object
becomes, in effect, uninitialized. A destroyed mutex object can be reinitialized using
pthread_mutex_init(); the results of otherwise referencing the object after it has been
destroyedareundefined.
intpthread_mutex_destroy(pthread_mutex_t*mutex);
CONCLUSION:
Thus,wehaveimplementedproducer-consumerproblemandReaderWriterProblem
using ‘C’ inLinux.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
FAQ
1. Explain the concept of semaphore.
2. Explain wait and signalfunctions associated withsemaphores.
3. What do binary and countingsemaphores mean?
Assignment No. 5
ImplementtheCprogramforDeadlockAvoidanceAlgorithm:BankersAlgorithm.
OBJECTIVE:ToStudy
Deadlock
DeadlockAvoidanceAlgorithm-BankersAlgorithm.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
THEORY:
What isDeadlock?
A set of processes is deadlocked if each process in the set is waiting for an event that only
another process in the set can cause. Because all the processes are waiting, none of them
wil ever cause any of the events that could wake up any of the other members of the set,
and all the processes continue to wait forever. For this model, we assume that processes
have only a single thread and that there are no interrupts possible to wake up a blocked
process. The no interrupts condition is needed to prevent an otherwise deadlocked
process from being awake.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Hold and wait condition- Processes currently holding resources granted earlier can
request new resources.
No preemption condition- Resources previously granted cannot be forcibly taken away
from aprocess. Theprocessholdingthemmustexplicitly release them.
Circular wait condition- There must be a circular chain of two or more processes, each
of whichis waitingfora resource held bythe next memberof the chain.
Banker’ s Algorithmin OperatingSystem
The banker’ s algorithm is a resource allocation and deadlock avoidance algorithm that
tests for safety by simulating the allocation for predetermined maximum possible amounts
of all resources, then makes an “s-state” check to test for possible activities, before
deciding whetherallocation shouldbe allowed tocontinue.
Why Banker’ s algorithmis named so?
Banker’ s algorithm is named so because it is used in banking system to check whether
loan canbe sanctioned to a personornot. Suppose there are numberof account holders
in a bank and the total sum of their money is . If a person applies for a loan then the bank
first subtracts the loan amount from the total money that bank has and if the remaining
amount is greater than S then only the loan is sanctioned. It is done because if all the
account holders comes to withdraw theirmoneythenthe bankcan easily do it.
In other words, the bank would never allocate its money in such a way that it canno longer
satisfythe needsof allits customers. The bank wouldtry to be in safe state always.
Following Data, structures are used to implement the Banker’ sAlgorithm:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Let ‘n’ be the number of processesinthe systemand ‘m’ be the number of
resourcestypes.
Available:
Itis a1-darrayofsize ‘m’ indicatingthenumberofavailableresourcesofeachtype.
Max:
Itis a2-darrayofsize ‘n*m’ thatdefinesthemaximumdemandofeachprocessina
system.
Max[i, j]=kmeansprocess Pi mayrequestatmost ‘k’ instancesofresourcetype Rj.
Allocation:
Itis a2-darrayofsize ‘n*m’ thatdefinesthenumberofresourcesofeachtype
currently allocatedtoeachprocess.
Allocation[i,j]=kmeansprocess Pi iscurrentlyallocated ‘k’ instancesof
resourcetype Rj
Need:
Itis a2-darrayofsize ‘n*m’ thatindicatestheremainingresourceneedofeach
process.
Need[i, j]=kmeansprocess Pi currentlyneed ‘k’ instancesofresourcetype Rj
Need[i, j]=Max[i, j]– Allocation[i, j]
Safety Algorithm
The algorithm for finding out whetheror not a system is in a safe state can be described
as follows:
Resource-Request Algorithm
Let Requesti be the request array forprocess Pi. Requesti [j] = k means process Pi wants
k instances of resource type Rj. When a request for resources is made by process Pi, the
following actions are taken:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Example-
Considering a system with five processes P0 through P4 and three resources of
type A, B, C. Resource type A has 10 instances, B has 5 instances and type C has
7 instances. Suppose at time t0 following snapshot of the system has been taken:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Question1. What will be the content of theNeed matrix?
Need [i, j] = Max[i, j] – Allocation [i, j]
So, the content of Need Matrix is:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
What will happen if process P1 requests one additional instance of resource type A
and two instancesof resourcetypeC
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
CONCLUSION:
Thus, we have implemented Banker’ s Algorithmproblemusing ‘C’ in Linux.
FAQ:
1. What is dead lock?
2. What are the necessaryand sufficient conditions tooccurdeadlock?
3. What is deadlock avoidance anddeadlock preventiontechniques?
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Assignment No. 6
ImplementtheC programforPageReplacementAlgorithms: FCFS, LRU,andOptimalfor
framesizeasminimumthree.
OBJECTIVE:
Tostudy
PageReplacement
MethodsandAlgorithmsforPageReplacement
THEORY:
PageReplacement
Acomputersystemhasalimitedamountofmemory.Addingmorememoryphysically isvery
costly.Therefore,mostmoderncomputersuseacombinationofbothhardwareandsoftware
toallow the computerto address more memory thanthe amount physicallypresent onthe
system.This extramemoryis actuallycalledVirtualMemory.
VirtualMemoryisastorageallocationschemeusedbytheMemoryManagementUnit(MMU)
tocompensate forthe shortage ofphysicalmemorybytransferringdatafromRAMtodisk
storage. It addresses secondarymemoryas though it is a part of the mainmemory. Virtual
Memorymakesthememoryappearlargerthanactuallypresentwhichhelpsin theexecution
ofprogramsthatarelargerthanthephysicalmemory.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Thepagereplacementalgorithmdecideswhichmemorypageistobereplaced.Theprocess
ofreplacementis sometimescalledswapoutorwritetodisk.Pagereplacementisdonewhen
therequestedpageis notfoundinthemain memory(pagefault).
InVirtualMemoryManagement,Page Replacement Algorithmsplayanimportant role.The
main objective of all the Page replacement policies is to decrease the maximum number
of pagefaults.
PageFault – Itis basically amemoryerror,andit occurswhenthecurrentprogramsattempt
toaccessthememorypageformappingintovirtualaddressspace,butit isunable toloadinto
thephysicalmemorythenthis isreferredtoasPagefault.
Apagefault happenswhenarunningprogramaccessesamemorypagethatis mappedinto
thevirtualaddressspace,butnotloadedin physicalmemory.
Sinceactualphysicalmemoryis muchsmallerthanvirtualmemory,pagefaultshappen.Incase
ofpagefault,OperatingSystemmighthavetoreplaceoneoftheexistingpageswiththenewly
neededpage.Differentpagereplacementalgorithmssuggestdifferentwaystodecidewhich
pagetoreplace.Thetargetforallalgorithmsis toreducethenumberofpagefaults.
VirtualMemorycanbeimplementedusingtwomethods:
Paging
Segmentation
Paging
Paging is aprocess of reading data from, andwriting datato,the secondarystorage. It isa
memorymanagementschemethatis usedtoretrieveprocessesfromthesecondarymemory
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
in theformofpagesandstorethemin theprimarymemory.Themain objectiveofpagingis to
divide each process in the formof pages of fixed size. These pages are stored in the main
memoryinframes.Pagesofaprocessareonlybroughtfromthe secondarymemorytothe
main memorywhentheyareneeded.
Whenanexecutingprocessreferstoapage,itisfirstsearchedin themain memory.Ifitisnot
presentinthemain memory,apagefault occurs.
PageFault is theconditionin whicharunningprocessreferstoapagethatisnotloadedin the
main memory.
Insuchacase,theOShastobringthepagefromthesecondarystorageintothemain memory.
Thismaycausesomepagesin themain memorytobereplacedduetolimitedstorage.APage
ReplacementAlgorithmisrequiredtodecidewhichpageneedstobereplaced.
BasicPageReplacementAlgorithminOS
Page Replacement Algorithm decideswhichpage toremove, also called swap out whena
newpageneedstobeloadedintothemain memory.
Whenthepagethatwasselectedforreplacementwaspagedout,andreferencedagain,it has
toreadinfromdisk,andthis requiresforI/Ocompletion.This processdeterminesthequalityof
the page replacement algorithm: the lesser the time waiting for page-ins, the better is the
algorithm.
PageReplacementtechniqueusesthefollowingapproach.If thereis nofreeframe,thenwe
wil findtheonethatisnotcurrently beingusedandthenfreeit.A-framecanbefreedbywriting
itscontenttoswapspaceandthenchangethe pagetable in ordertoindicatethatthepageis
nolongerin thememory.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
1. Firstofall,findthelocationofthedesiredpageonthedisk.
2. FindafreeFrame:a)Ifthereis afreeframe,thenuseit.b)Ifthereis nofreeframethen
make use of the page-replacement algorithm in order to select the victim frame. c)
Thenafterthatwritethevictim frametothediskandthenmakethechangesinthepage
table andframetable accordingly.
3. Afterthatreadthedesiredpageintothenewly freedframeandthenchangethepage
andframetables.
4. Restarttheprocess.
Figure:PageReplacement
PageReplacementAlgorithmsinOS
Thisalgorithmhelpstodecide whichpagesmustbe swappedoutfromthemain memoryin
ordertocreatearoomfortheincomingpage.This Algorithmwantsthelowestpage-fault rate.
VariousPageReplacementalgorithmsusedin theOperatingsystemareasfollows;
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
SomePageReplacementAlgorithms:
FirstInFirstOut(FIFO)
LeastRecently Used(LRU)
OptimalPageReplacement
1.FirstInFirstOut(FIFO)
Itis averysimple wayofPagereplacementandis referredtoasFirstin FirstOut.This algorithm
mainly replacestheoldestpagethathasbeenpresentinthemain memoryforthelongesttime.
Thisalgorithmisimplementedbykeepingthetrackofall thepagesin thequeue.
Asnewpagesarerequestedandareswappedin,theyareaddedtothetailofaqueue
andthepagewhichis attheheadbecomesthevictim.
Thisis notaneffectivewayofpagereplacementbutitcanbeusedforsmallsystems.
Advantages
Thisalgorithmissimpleandeasytouse.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
FIFOdoesnotcausemoreoverhead.
Disadvantages
Thisalgorithmdoesnot make the useofthe frequencyof lastusedtime rather it just
replacestheOldestPage.
Thereis anincreasein pagefaults aspageframesincreases.
ALGORITHM
1.Starttheprocess
2.Declarethesizewithrespecttopagelength
3.Checktheneedofreplacementfromthepagetomemory
4.Checktheneedofreplacementfromoldpagetonewpagein memory
5.Formaqueuetohold all pages
6.Insertthepagerequirememoryintothequeue
7.Checkforbadreplacementandpagefault
8.Getthenumberofprocessestobeinserted
9.Displaythevalues
10.Stoptheprocess
CodeofFIFOPageReplacementAlgorithm
#include<stdio.h>
intmain()
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
{
inti,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\nENTERTHENUMBEROFPAGES:\n");
scanf("%d",&n);
printf("\nENTERTHEPAGENUMBER:\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\nENTERTHENUMBEROFFRAMES:");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]=-1;
j=0;
printf("\trefstring\tpageframes\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("PageFault Is%d",count);
return0;
}
OUTPUT
ENTERTHENUMBEROFPAGES: 20
ENTERTHEPAGENUMBER: 7012030423032120170 1
ENTERTHENUMBEROFFRAMES:3
refstring pageframes
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1
PageFaultIs15
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Assignment No. 7
InterProcessCommunication(IPC)in Linuxusingfollowing.
A. FIFOS:Full duplexcommunicationbetweentwoindependentprocesses.Firstprocess
acceptssentencesandwritesonone pipetobereadbysecondprocessandsecond
processcountsumberofcharacters,numberofwordsandnumberoflinesin accepted
sentences,writesthis outputin atextfileandwritesthecontentsofthefileonsecond
pipetobereadbyfirstprocessanddisplaysonstandardoutput.
B. Inter-processCommunicationusingShared Memory using System V. Application to
demonstrate: Client and Server Programs in whichserver processcreates a shared
memory segment and writes the message to the shared memory segment. Client
processreads themessage fromthe shared memorysegment and displays it tothe
screen.
OBJECTIVE:
Tostudy
Communication(interface)betweenprocesses.
FIFOmethodofprocesscommunication.
Sharedmemoryprocessofcommunication
THEORY:
Inter process communication in Linux
Firstinfirstout(FIFO)
AFIFO(FirstInFirstOut)isaone-wayflowofdata.FIFOshaveaname,sounrelatedprocesses
cansharetheFIFO.FIFOis anamedpipe.AnyprocesscanopenorclosetheFIFO.FIFOsare
alsocallednamedpipes.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Properties:
1. AfteraFIFOis created,it canbeopenedforreadorwrite.
2. Normally,openingaFIFOforreadorwrite,it blocksuntil anotherprocessopensit for
writeorread.
1. Areadgetsasmuchdataasit requestsorasmuchdataastheFIFOhas,whicheveris
less.
2. AwritetoaFIFOisatomic,aslongasthewritedoesnotexceedthecapacityoftheFIFO.
3. TwoprocessesmustopenFIFO;oneopensit asreaderononeend,theotheropensit
as senderonthe otherend.Thefirst/earlieropenerhastowait until the second/later
openertocome.This is somewhatlikeahandshaking.
CreatingaFIFO
AFIFOis createdbythemkfifofunction.SpecifythepathtotheFIFOonthecommandline.For
example,createaFIFOin/tmp/fifobyinvokingthis:
#include<sys/types.h>
#include<sys/stat.h>
intmkfifo(constchar*pathname,mode_tmode);
pathname:aUNIXpathname(pathandfilename).ThenameoftheFIFO
mode:thefile permissionbits.Itspecifiesthepipe’ sowner, group,andworld permissions,
andapipemusthaveareaderandawriter,thepermissionsmustincludebothreadandwrite
permissions.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
A FIFO can have multiple readers or multiple writers. Bytes from each writer are written
atomically up to a maximum size of PIPE_BUF (4KB on Linux). Chunks from simultaneous
writerscanbeinterleaved.Similarrulesapply tosimultaneousreads.
Close:TocloseanopenFIFO,useclose().
Unlink:TodeleteacreatedFIFO,useunlink().
Inter-processCommunicationusingSharedMemoryusingSystemV.
Sharedmemoryis oneofthethreeinter-processcommunication(IPC)mechanismsavailable
under Linux and other Unix-like systems. The othertwo IPC mechanisms are the message
queuesandsemaphores.Incaseofsharedmemory,asharedmemorysegmentis createdby
thekernelandmappedtothedatasegmentoftheaddressspaceofarequestingprocess.A
processcanusethesharedmemoryjustlikeanyotherglobalvariable in itsaddressspace.
Intheinter-processcommunicationmechanismslikethepipes,fifosandmessagequeues,the
work involved in sending data from one process to another is like this. Process makes a
systemcall tosenddatatoProcess .Themessageis copiedfromtheaddressspaceofthe
firstprocess tothe kernel space duringthe system call for sendingthe message. Then, the
secondprocessmakesasystemcalltoreceivethemessage.Themessageiscopiedfromthe
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
kernelspace to the address space of the secondprocess. Thesharedmemorymechanism
doesawaywiththis copyingoverhead. The first processsimply writesdata intotheshared
memorysegment.Assoonasit is written,thedatabecomesavailable tothesecondprocess.
Sharedmemoryis thefastestmechanismforinter-processcommunication.
Weknowthattocommunicatebetweentwoormoreprocesses,weusesharedmemorybut
beforeusingthesharedmemorywhatneedstobedonewiththesystemcalls,letusseethis−
Create the shared memory segment or use an already created shared memory
segment(shmget())
Attachtheprocesstothealreadycreatedsharedmemorysegment(shmat())
Detachtheprocessfromthealreadyattachedsharedmemorysegment(shmdt())
Controloperationsonthesharedmemorysegment(shmctl())
Letuslookatafewdetails ofthesystemcallsrelatedtosharedmemory.
#include<sys/ipc.h>
#include<sys/shm.h>
intshmget(key_tkey,size_tsize,intshmflg)
The above system call creates or allocates a System V shared memory segment. The
argumentsthatneedtobepassedareasfollows−
The firstargument,key, recognizesthesharedmemorysegment.Thekeycanbeeitheran
arbitraryvalueoronethatcanbederivedfromthe libraryfunctionftok().Thekeycanalsobe
IPC_PRIVATE,means,runningprocessesasserverandclient(parentandchild relationship)
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
i.e.,inter-relatedprocess communiation. Ifthe clientwantstouse sharedmemorywiththis
key, thenit mustbeachild processof the server.Also, the childprocessneedstobecreated
aftertheparenthasobtainedasharedmemory.
The secondargument,size, isthesizeofthesharedmemorysegmentroundedtomultiple of
PAGE_SIZE.
The third argument, shmflg, specifies the required shared memory flag/s such as
IPC_CREAT (creating new segment) or IPC_EXCL (Used with IPC_CREAT to create new
segmentandthecall fails,if thesegmentalreadyexists).Needtopassthepermissionsaswell.
This call would return a valid shared memory identifier (used for further calls of shared
memory)onsuccessand-1in caseoffailure.Toknowthecauseoffailure,checkwitherrno
variableorperror()function.
#include<sys/types.h>
#include<sys/shm.h>
void *shmat(intshmid,constvoid *shmaddr,intshmflg)
The above system call performs shared memory operation for System V shared memory
segmenti.e.,attachingasharedmemorysegmenttotheaddressspaceofthecallingprocess.
Theargumentsthatneedtobepassedareasfollows−
shmid is theidentifierofthesharedmemorysegment.This idis thesharedmemoryidentifier,
whichis thereturnvalueofshmget()systemcall.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
shmaddr is to specify the attaching address. If shmaddr is NULL, the system by default
choosesthesuitable addresstoattachthesegment.Ifshmaddris notNULLandSHM_RNDis
specified in shmflg, the attach is equal to the address of the nearest multiple of SHMLBA
(LowerBoundaryAddress).Otherwise,shmaddrmustbeapagealignedaddressatwhichthe
sharedmemoryattachmentoccurs/starts.
shmflgis specifies the required shared memory flag/s such as SHM_RND (rounding off
address to SHMLBA) or SHM_EXEC (allows the contents of segment to be executed) or
SHM_RDONLY (attachesthe segment forread-only purpose, by default it isread-write) or
SHM_REMAP (replaces the existing mapping in the range specified by shmaddr and
continuingtil theendofsegment).
Thiscall would returntheaddressofattachedsharedmemorysegmentonsuccessand-1in
caseoffailure.Toknowthecauseoffailure,checkwitherrnovariableorperror()function.
#include<sys/types.h>
#include<sys/shm.h>
intshmdt(constvoid *shmaddr)
he above system call performs shared memory operation for System V shared memory
segment of detaching the shared memory segment from the address space of the calling
process.Theargumentthatneedstobepassedis −
The argument, shmaddr, is the address of shared memory segment to be detached. The
to-be-detachedsegmentmustbetheaddressreturnedbytheshmat()systemcall.
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Thiscallwould return0onsuccessand-1incaseoffailure.Toknowthecauseoffailure,check
witherrnovariable orperror()function.
#include<sys/ipc.h>
#include<sys/shm.h>
intshmctl(intshmid,intcmd,structshmid_ds*buf)
anotherisforreadingfromthesharedmemory(shm_read.c)
Theprogramperformswritingintothesharedmemorybywriteprocess(shm_write.c)
andreadingfromthesharedmemorybyreadingprocess(shm_read.c)
Inthesharedmemory, the writingprocess,createsasharedmemoryofsize 1K(and
flags)andattachesthesharedmemory
The write process writes 5 times the Alphabets from ‘A’ to ‘E’ each of 1023
bytesintothesharedmemory.Lastbytesignifiestheendofbuffer
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Readprocesswould readfromthesharedmemoryandwritetothestandardoutput
Readingandwritingprocessactionsareperformedsimultaneously
Aftercompletionofwriting,thewriteprocessupdatestoindicatecompletionofwriting
intothesharedmemory(withcompletevariableinstructshmseg)
Reading process performs reading from the shared memory and displays on the
toavoid infiniteloopsandcomplicatingtheprogram
Codeforwriteprocess(WritingintoSharedMemory– File:shm_write.c)
/*Filename:shm_write.c*/
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#defineBUF_SIZE1024
#defineSHM_KEY0x1234
structshmseg{
intcnt;
intcomplete;
charbuf[BUF_SIZE];
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
};
intfill_buffer(char*bufptr,intsize);
intmain(intargc,char*argv[]){
intshmid,numtimes;
structshmseg*shmp;
char*bufptr;
intspaceavailable;
shmid=shmget(SHM_KEY,sizeof(structshmseg),0644|IPC_CREAT);
if (shmid ==-1){
perror("Sharedmemory");
return1;
}
//Attachtothesegmenttogetapointertoit.
shmp=shmat(shmid,NULL,0);
if (shmp==(void *)-1){
perror("Sharedmemoryattach");
return1;
}
/*Transferblocksofdatafrombuffertosharedmemory*/
bufptr=shmp->buf;
spaceavailable =BUF_SIZE;
for(numtimes=0;numtimes<5;numtimes++){
shmp->cnt=fil _buffer(bufptr,spaceavailable);
shmp->complete=0;
printf("WritingProcess:SharedMemoryWrite:Wrote%dbytes\n",shmp->cnt);
bufptr=shmp->buf;
spaceavailable =BUF_SIZE;
sleep(3);
}
printf("WritingProcess:Wrote%dtimes\n",numtimes);
shmp->complete=1;
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
if (shmdt(shmp)==-1){
perror("shmdt");
return1;
}
if (shmctl(shmid,IPC_RMID,0)==-1){
perror("shmctl");
return1;
}
printf("WritingProcess:Complete\n");
return0;
}
intfill_buffer(char*bufptr,intsize){
staticcharch='A';
intfilled_count;
//printf("sizeis %d\n",size);
memset(bufptr,ch,size-1);
bufptr[size-1]='\0';
if (ch>122)
ch=65;
if ((ch>=65)&&(ch<=122)){
if ((ch>=91)&&(ch<=96)){
ch=65;
}
}
fil ed_count=strlen(bufptr);
//printf("buffercountis:%d\n",filled_count);
//printf("bufferfilledis:%s\n",bufptr);
ch++;
returnfilled_count;
}
CompilationandExecutionSteps
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
WritingProcess:SharedMemoryWrite:Wrote1023bytes
WritingProcess:SharedMemoryWrite:Wrote1023bytes
WritingProcess:SharedMemoryWrite:Wrote1023bytes
WritingProcess:SharedMemoryWrite:Wrote1023bytes
WritingProcess:SharedMemoryWrite:Wrote1023bytes
WritingProcess:Wrote5times
WritingProcess:Complete
Codefor read process (ReadingfromtheShared Memory and writingto thestandard
output– File:shm_read.c)
/*Filename:shm_read.c*/
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#defineBUF_SIZE1024
#defineSHM_KEY0x1234
structshmseg{
intcnt;
intcomplete;
charbuf[BUF_SIZE];
};
intmain(intargc,char*argv[]){
intshmid;
structshmseg*shmp;
shmid=shmget(SHM_KEY,sizeof(structshmseg),0644|IPC_CREAT);
if (shmid ==-1){
perror("Sharedmemory");
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
return1; }
//Attachtothesegmenttogetapointertoit.
shmp=shmat(shmid,NULL,0);
if (shmp==(void *)-1){
perror("Sharedmemoryattach");
return1; }
/*Transferblocksofdatafromsharedmemorytostdout*/
while (shmp->complete!=1){
printf("segmentcontains:\n\"%s\"\n",shmp->buf);
if (shmp->cnt==-1){
perror("read");
return1; }
printf("ReadingProcess:SharedMemory:Read%dbytes\n",shmp->cnt);
sleep(3);
}
printf("ReadingProcess:ReadingDone,DetachingSharedMemory\n");
if (shmdt(shmp)==-1){
perror("shmdt");
return1;
}
printf("ReadingProcess:Complete\n");
return0;
}
CONCLUSION:
Thus,westudiedinterprocesscommunicationusingFIFOs
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Assignment No. 8
ImplementtheCprogramforDiskSchedulingAlgorithms:SSTF,SCAN,C-Lookconsidering
theinitialheadpositionmovingawayfromthespindle.
OBJECTIVE:
This assignment covers the UNIX process control commonly called for process creation,
programexecutionandprocess termination.Also coversprocess model, including process
creation,processdestruction,zombie andorphanprocesses.
THEORY:
DiskSchedulingAlgorithms
Diskscheduling is done byoperating systems to schedule I/O requests arriving for the
disk. Disk scheduling is also knownas I/O scheduling.
Diskscheduling is important because:
Multiple I/O requests may arrive bydifferent processes and onlyone I/O request
canbe served at a time bythe disk controller. Thus other I/O requests need to wait
in the waiting queue andneed tobe scheduled.
Two or more request may be far from eachothersocan result in greaterdiskarm
movement.
Hard drives are one of the slowest parts of the computersystem and thus need to
where the dataisto be read or write. So the disk scheduling algorithmthat gives
minimumaverage seek time isbetter.
Rotational Latency: Rotational Latencyisthe time taken bythe desired sector of
disk torotate into a positionsothat it canaccess the read/write heads. So the disk
scheduling algorithm that gives minimumrotational latency is better.
Transfer Time: Transfer time is the time to transfer the data. Itdependsonthe
Disk Response Time: Response Time is the average of time spent by a request
waiting to perform its I/O operation. is the response time of
the all requests. is measure of how individual request are
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
serviced with respect to average response time. Therefore, the disk scheduling
algorithmthat givesminimum variance response time is better.
Disk SchedulingAlgorithms
FCFS:
FCFS is the simplest ofall the Disk SchedulingAlgorithms. In FCFS, the requests are
addressed inthe ordertheyarrive in the diskqueue. Let us understand thiswiththe help of
an example.
Example:
Suppose the order of request is- (82,170,43,140,24,16,190)
And current positionof Read/Write headis: 50
Advantages:
Everyrequest gets a fair chance
No indefinite postponement
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Disadvantages:
Does not tryto optimize seek time
Maynot provide the best possible service
SSTF: In SSTF (Shortest Seek Time First), requests having shortest seek time are
executed first. So, the seek time of every request is calculated in advance in the queue and
then they are scheduled according to their calculated seek time. As a result, the request
near the disk arm will get executed first. SSTF is certainly an improvement over FCFS as it
decreases the average response time and increases the throughput of system.Let us
understand this with the help of an example.
Example:
Suppose the order of request is- (82,170,43,140,24,16,190)
And current positionof Read/Write headis: 50
So,totalseektime:
=(50-43)+(43-24)+(24-16)+(82-16)+(140-82)+(170-40)+(190-170)=208
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Advantages:
AverageResponseTimedecreases
Throughputincreases
Disadvantages:
Overheadtocalculateseektimein advance
CancauseStarvationforarequestif ithashigherseektimeascomparedtoincoming
requests
HighvarianceofresponsetimeasSSTFfavorsonlysomerequests
SCAN: In SCAN algorithm the disk arm moves into a particular direction and services the
requests coming in its path and after reaching the end of disk, it reverses its direction and
againservices the request arriving inits path. So, this algorithm works as anelevator and
hence also known as elevator algorithm. As a result, the requests at the midrange are
serviced more and those arriving behind the disk arm will have to wait.
Example:
Supposetherequeststobeaddressedare-82,170,43,140,24,16,190.Inaddition,the
Read/Writearmisat50,andit is giventhatthediskarmshouldmove “towardsthelarger
value” .
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Disadvantages:
Long waiting time for requests for locations just visited bydisk arm
LOOK: It is similar to the SCAN disk-scheduling algorithm except for the difference that
the disk arm in spite of going to the end of the disk goes only to the last request to be
serviced in front of the head and then reverses its direction from there only. Thus, it
prevents the extra delay that occurred due to unnecessary traversal to the end of the
disk.
Example:
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Suppose the requests to be addressed are-82, 170,43,140,24,16,190. In addition, the
Read/Write arm is at 50, and it is given that the disk arm should move “towards the
larger value” .
Page of 100
PEOPLES EMPOWERMENT GROUP
ISBM COLLEGE OF ENGINEERING, NANDE, PUNE
DEPARTMENT OF ARTIFICIALINTELLIGENCE&MACHINELEARNING
Page of 100