operating system laboratory manual

57
cseitquestions.blogspot.in | cseitquestions.blogspot.in  | cseitquestions.blogspot.in  1 K.L.N. COLLEGE OF ENGINEERING Pottapal ayam Pos t - 630 612. S i vagangai D i s tr i ct , Tamil N adu. DEPARTMENT OF INFORMATION TECHNOLOGY I T6412-OPERATI NG S YS TEM M AN UA L Staff In-Charges and Prepared by Mrs.C.Manjula Devi, AP2/IT III Year/V Semester (July 2015-November 2015)

Upload: priya-raji

Post on 25-Feb-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 1/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

1

K.L.N. COLLEGE OF ENGINEERING

Pottapalayam Post - 630 612.Sivagangai Distr ict, Tamil Nadu.

DEPARTMENT OF INFORMATION TECHNOLOGY

I T6412-OPERATI NG SYSTEM MANUAL

Staff In-Charges and Prepared by

Mrs.C.Manjula Devi, AP2/IT

III Year/V Semester

(July 2015-November 2015)

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 2/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

2

ANNA UNIVERSITY, CHENNAI REGULATION 2013

B.TECH INFORMATION TECHNOLOGY

SYLLABUS

IT6412 OPERATING SYSTEMS LAB 0 0 3 2

(Common to CSE & IT)

OBJECTIVES:

The student should be made to:

  Learn shell programming and the use of filters in the UNIX environment.

  Be exposed to programming in C using system calls.

  Learn to use the file system related system calls.

  Be exposed to process creation and inter process communication.

  Be familiar with implementation of CPU Scheduling Algorithms, page replacement

algorithms and Deadlock avoidance

LIST OF EXPERIMENTS:

1.  Basics of UNIX commands.2.  Shell Programming.3.  Implement the following CPU scheduling algorithms

a)  Round Robin b) SJF c) FCFS d) Priority4.  Implement all file allocation strategies

a)  Sequential b) Indexed c) Linked5.  Implement Semaphores6.  Implement all File Organization Techniques

a)  Single level directory b) Two level c) Hierarchical d) DAG7.  Implement Bankers Algorithm for Dead Lock Avoidance8.  Implement an Algorithm for Dead Lock Detection9.  Implement e all page replacement algorithms

a)  FIFO b) LRU c) LFU10. Implement Shared memory and IPC11. Implement Paging Technique of memory management.12. Implement Threading & Synchronization Applications

TOTAL: 45 PERIODS

OUTCOMES:

At the end of the course, the student should be able to

  Implement deadlock avoidance, and Detection Algorithms  Compare the performance of various CPU Scheduling Algorithm

  Critically analyze the performance of the various page replacement algorithms

  Create processes and implement IPC

REFERENCE:

spoken-tutorial.org

LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 3/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

3

Standalone desktops with C / C++ / Java / Equivalent complier 30 Nos.(or)

Server with C / C++ / Java / Equivalent complier supporting 30 terminals

Syllabus downloaded from www.annauniv.edu

Ex.No : 1 UNIX COMMANDS

I. Basic Commands:

1.  Echo Command :This command is used to print the arguments on the screen .

Syntax : $echo <text>

Multi line echo command :To have the output in the same line , the following commands can be used.

Syntax : $echo <text\>textTo have the output in different line, the following command can be used.Syntax : $echo “text>line2>line3” 

2.  ’who’ Command :

It is used to display who are the users connected to our computer currently.

List of Experiments

1. Basics of UNIX commands

2. Shell Programming

3.Implement the following CPU scheduling algorithms

a)  Round Robin b) SJF c) FCFS d) Priority

4.

Implement all file allocation strategies

 b)  Sequential b) Indexed c) Linked

5. Implement Semaphores

6.Implement all File Organization Techniques

Single level directory b) Two level c) Hierarchical d) DAG

7. Implement Bankers Algorithm for Dead Lock Avoidance

8. Implement an Algorithm for Dead Lock Detection

9.Implement e all page replacement algorithms

a)  FIFO b) LRU c) LFU

10. Implement Shared memory and IPC

11. Implement Paging Technique of memory management.

12. Implement Threading & Synchronization Applications

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 4/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

4

Syntax : $who –  optionsOptions : -

H – Display the output with headers. b – Display the last booting date or time or when the system was lastely rebooted.

3. ’who am i’ Command :

Display the details of the current working directory.Syntax : $who am i4.  ’tty’ Command :

It will display the terminal name.Syntax : $tty

5.  ’Binary’ Calculator Command :

It will change the $ mode and in the new mode, arithematic operations such as +,-,*,/,%,n,sqrt(),length(),=, etc can be performed . This command is used to go to the binarycalculus mode.

Syntax :$bc operations^d$1 base – inputbase0 base –  outputbase are used for base conversions.Base :Decimal = 1 Binary = 2 Octal = 8 Hexa = 16

II. DIRECTORY RELATED COMMANDS :

1.Present Working Directory Command :

To print the complete path of the current working directory.Syntax : $pwd

2.MKDIR Command :To create or make a new directory in a current directory .

Syntax : $mkdir <directory name>3.CD Command :To change or move the directory to the mentioned directory .

Syntax : $cd <directory name.4.RMDIR Command :To remove a directory in the current directory & not the current directory itself.

Syntax : $rmdir <directory name>

III. FILE RELATED COMMANDS :

1.CREATE A FILE :To create a new file in the current directory we use CAT command.

Syntax :

$cat > <filename.The > symbol is redirectory we use cat command.

2.DISPLAY A FILE :To display the content of file mentioned we use CAT command without > operator.

Syntax :$cat <filename.Options – s = to neglect the warning /error message.

3.COPYING CONTENTS :

To copy the content of one file with another. If file doesnot exist, a new file is created and if thefile exists with some data then it is overwritten.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 5/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

5

Syntax :$ cat <filename source> >> <destination filename>$ cat <source filename> >> <destination filename> it is avoid overwriting.Options : --n content of file with numbers included with blank lines.

Syntax :$cat – n <filename>4.SORTING A FILE :To sort the contents in alphabetical order in reverse order.

Syntax :$sort <filename >Option : $ sort – r <filename>

5.COPYING CONTENTS FROM ONE FILE TO ANOTHER :To copy the contents from source to destination file . so that both contents are same.

Syntax :$cp <source filename> <destination filename>$cp <source filename path > <destination filename path>

6.MOVE Command :To completely move the contents from source file to destination file and to remove the sourcefile.

Syntax :$ mv <source filename> <destination filename>

7.REMOVE Command :To permanently remove the file we use this command .

Syntax :$rm <filename>

8. WORD Command :

To list the content count of no of lines , words, characters .Syntax :$wc<filename>Options :-c –  to display no of characters.-l –  to display only the lines.-w –  to display the no of words.

9. LIST Command :It is used to list all the contents in the current working directory.

Syntax : $ ls –  options <arguments>

If the command does not contain any argument means it is working in the Current directory.Options :a –  used to list all the files including the hidden files.c –  list all the files columnwise.d- list all the directories.m- list the files separated by commas.

 p- list files include / to all the directories.r- list the files in reverse alphabetical order.f- list the files based on the list modification date.x-list in column wise sorted order.

VI .Date Command :This command is used to display the current data and time.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 6/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

6

Syntax :$date$date +%chOptions : -a = Abbrevated weekday.

A = Full weekday. b = Abbrevated month.B = Full month.c = Current day and time.C = Display the century as a decimal number.d = Day of the month.D = Day in mm/dd/yy formath = Abbrevated month day.H = Display the hour.L = Day of the year.m = Month of the year.M = Minute.P = Display AM or PMS = SecondsT = HH:MM:SS formatu = Week of the year.y = Display the year in 2 digit.Y = Display the full year.Z = Time zone .

To change the format :

Syntax :

$date +%H-%M-%S

2.Calender Command :

This command is used to display the calendar of the year or the particular month of calendaryear.

Syntax :a.$cal <year>

 b.$cal <month> <year>Here the first syntax gives the entire calendar for given year & the second Syntax gives the calendarof reserved month of that year.

V. FILTERS AND PIPES

1.HEAD : It is used to display the top ten lines of file.

Syntax: $head<filename>2.TAIL : This command is used to display the last ten lines of file.

Syntax: $tail<filename>3.PAGE : This command shows the page by page a screenfull of information is displayed afterwhich the page command displays a prompt and passes for the user to strike the enter key tocontinue scrolling.

Syntax: $ls – a\p4.MORE : It also displays the file page by page .To continue scrolling with more command ,

 press the space bar key.Syntax: $more<filename>

6.  PIPE : It is a mechanism by which the output of one command can be channeled into the

input of another command.Syntax: $who | wc-l

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 7/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

7

VI. SEARCHING AND SORTING COMMANDS1.  GREP :This command is used to search and print the specified patterns from the file.

Syntax: $grep [option] pattern <filename>

‘grep’ command 

- grep command searches the given file for lines containing a match to the given strings orwords. By default, grep prints the matching lines. Use grep to search for lines of text that matchone or many regular expressions, and outputs only the matching lines. The name, "grep", derivesfrom the command used to perform a similar operation, using the Unix/Linux text editor ed:

 g/re/p

Syntax

grep 'word' filenamegrep 'string1 string2' filenamecat otherfile | grep  'something'

command | grep 'something'

2. SORT : This command is used to sort the datas in some order.Syntax: $sort<filename>

V. FILE PERMISSION COMMANDS

SYNTAX: $chmod mode filenameDESCRIPTION: This command is used to alter the access permissions for the owner groups and others for a file.

MODES:

a)  ABSOLUTE MODE:SYNTAX: $chmod <octal representation> filenameDESCRIPTION: This mode uses number to alter permissions for a file or for all the users.

OCTAL MEANING4 Read permissions2 Write1 Execute0 No permissions

Eg: $chmod 644 file.cDESCRIPTION: Read and write to owner and read to groups and others.

 b)  SYMBOLIC MODE:SYNTAX: $chmod <type of user><operation><access permission> filenameDESCRIPTION: This mode uses letters to alter permissions for a file and for all users.

CHARATER- TYPE OF USERu- denotes user or owner of the fileg- denotes group to which the user belongs too- denotes users excluding owner and members iroupa-  Denotes all users including owner, group and others.

CHARATER- ACCESS PERMISSIONr- sets read permissionw- sets write permissionv- sets execute permission

CHARATER- ACTION TO BE PERFORMED+ assigns permissions for the specified user-  removes permission from the specified user

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 8/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

8

= Assign permission for the specified userEg: $chmod u+x file.cDESCRIPTION: Assigns execute permission to user only. To check the access permissions, use this command.FOR Eg: ls.l file

GENERAL PURPOSE COMMANDS:

SYNTAX: $who | wcDESCRIPTION: This command first executes who and the result is transformed to the input of word countcommand.

vi EDITOR

DESCRIPTION :The Vi editor is a visual editor used to create and edit text, files, documents and programs. It displays the content of files on the screen and allows a user to add, delete orchange part of text . There are three modes available in the Vi editor , they are

1.Command mode2.Input (or) insert mode.

Starting Vi :The Vi editor is invoked by giving the following commands in UNIX prompt.Syntax : $vi <filename> (or)

$viThis command would open a display screen with 25 lines and with tilt (~) symbol at the

start of each line. The first syntax would save the file in the filename mentioned and for the

next the filename must be mentioned at the end.Options :

1.vi +n <filename> - this would point at the nth line (cursor pos).2.vi – n <filename> - This command is to make the file to read only to change from onemode to another press escape key.

INSERTING AND REPLACING COMMANDS :To move editor from command node to edit mode, you have to press the <ESC> key.

For inserting and replacing the following commands are used.1.ESC a Command :

This command is used to move the edit mode and start to append after the current

character.Syntax : <ESC> a

2.ESC A COMMAND :This command is also used to append the file , but this command append at the end of

current line.Syntax : <ESC> A

3.<ESC> j :This command is used to move down a single line or a number of lines.Syntax :

<ESC> j –  single down movement.<ESC> nj –  n times down movement.

4.<ESC> k :This command is used to move up a single line or a number of lines.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 9/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

9

Syntax :<ESC> k –  single line above.<ESC> nk –  n lines above.

5.ENTER (OR) N ENTER :This command will move the cursor to the starting of next lines or a group of lines

mentioned.Syntax :<ESC> enter <ESC> n enter.

6.<ESC> + Command :This command is used to move to the beginning of the next line.Syntax :<ESC> + <ESC> n+

7.<ESC> - Command :This command is used to move to the beginning of the previous line.Syntax :<ESC> - <ESC> n-

8.<ESC> 0 :This command will bring the cursor to the beginning of the same current line.Syntax :<ESC> 0

9.<ESC> $ :This command will bring the cursor to the end of the current line.

Syntax :<ESC> $

10.<ESC> ^ :This command is used to move to first character of first lines.

Syntax :<ESC> ^

11.<ESC> b Command :This command is used to move back to the previous word (or) a number of words.Syntax :<ESC> b <ESC>nb

12.<ESC> e Command :This command is used to move towards and replace the cursor at last character of the

word (or) no of words.Syntax :

<ESC> e <ESC>ne13.<ESC> w Command :

This command is used to move forward by a single word or a group of words.

Syntax :<ESC> w <ESC> nw

DELETING THE TEXT FROM Vi :

1.<ESC> x Command :To delete a character to right of current cursor positions , this command is used.Syntax :<ESC> x <ESC> nx

2.<ESC> X Command :To delete a character to left of current cursor positions , this command is used.Syntax :<ESC> X <ESC> nX

3.<ESC> dw Command :

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 10/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

10

This command is to delete a single word or number of words to right of current cursor position.

Syntax :<ESC> dw <ESC> ndw

4.db Command :

This command is to delete a single word to the left of the current cursor position.Syntax :<ESC> db <ESC> ndb

5.<ESC> dd Command :This command is used to delete the current line (or) a number of line below the current

line.Syntax :<ESC> dd <ESC> ndd

6.<ESC> d$ Command :This command is used to delete the text from current cursor position to last character of

current line.Syntax : <ESC> d$

SAVING AND QUITING FROM vi :-

1.<ESC> w Command :To save the given text present in the file.Syntax : <ESC> : w

2.<ESC> q! Command :To quit the given text without saving.Syntax : <ESC> :q!

3.<ESC> wq Command :

This command quits the vi editor after saving the text in the mentioned file.Syntax : <ESC> :wq

4.<ESC> x Command :This command is same as wq command it saves and quit.Syntax : <ESC> :x

5.<ESC> q Command :This command would quit the window but it would ask for again to save the file.Syntax : <ESC> : q

Ex.No : 2 SHELL PROGRAMMING

a)  COMPARISON OF TWO STRINGS

Aim:To write a shell program to compare the two strings.

Algorithm:Step1: Enter into the vi editor and go to the insert mode for entering the codeStep2: Read the first string.Step3: Read the second stringStep4: Compare the two strings using the if loopStep5: If the condition satisfies then print that two strings are equal else print twostrings are not equal.Step6: Enter into the escape mode for the execution of the result and verify the output

Program:

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 11/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

11

echo “enter the first string”read str1echo “enter the second string”read str2if [ $str1 = $str2 ]

thenecho “strings are equal”elseecho “strings are unequal”fi

Sample I/P:1Enter first string: haiEnter second string: haiSample O/P:1The two strings are equalSample I/P:2

Enter first string: haiEnter second string: cseSample O/P:2The two strings are not equal

Result:Thus the shell program to compare the two strings is executed and output is verified successfully.

b)  MAXIMUM OF THREE NUMBERS

Aim:

To write a shell program to find greatest of three numbers.

Algorithm:Step1: Declare the three variables.Step2: Check if A is greater than B and C.Step3: If so print A is greater.Step4: Else check if B is greater than C.Step5: If so print B is greater.Step6: Else print C is greater.

Program:

echo "enter A"read aecho "enter B"

read becho "enter C"read cif [ $a -gt $b -a $a -gt $c ]thenecho "A is greater"elif [ $b -gt $a -a $b -gt $c ]thenecho "B is greater"elseecho "C is greater"

fiSample I/P:

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 12/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

12

Enter A:23Enter B:45Enter C:67Sample O/P: C is greater

Result:

Thus the shell program to find the maximum of three numbers is executed and output is verifiedsuccessfully.

c)  FIBONACCI SERIES

Aim:To write a shell program to generate fibonacci series.

Algorithm :Step 1 : Initialise a to 0 and b to 1.Step 2 : Print the values of 'a' and 'b'.Step 3 : Add the values of 'a' and 'b'. Store the added value in variable 'c'.Step 4 : Print the value of 'c'.

Step 5 : Initialise 'a' to 'b' and 'b' to 'c'.Step 6 : Repeat the steps 3,4,5 till the value of 'a' is less than 10.

Program :echo enter the numberread na=-1

 b=1i=0while [ $i – le $n ]dot=`expr $a + $b`

echo $ta=$b

 b=$ti=`expr $i + 1done

Sample I/P :Enter the no: 5Sample O/P:011

235Result :

Thus the shell program to find the fibonacci series is executed and output is verifiedsuccessfully.

d)  ARITHMETIC OPERATIONS USING CASE

Aim:To write a shell program to perform the arithmetic operations using case

Algorithm :Step 1 : Read the input variables and assign the valueStep 2 : Print the various arithmetic operations which we are going to performStep 3 : Using the case operator assign the various functions for the arithmetic

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 13/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

13

operators.Step 4 : Check the values for all the corresponding operations.Step 5 : Print the result and stop the execution.

Program :

echo 1.Additionecho 2.Subractionecho 3.Multiplicationecho 4.Divisionecho enter your choiceread aecho enter the value of bread becho enter the value of cread cecho b is $b c is $ccase $a in1)d=`expr $b + $c`echo the sum is $d;;2)d=`expr $b - $c`echo the difference is $d;;3)d=`expr $b \* $c`echo the product is $d;;4)d=`expr $b / $c`echo the quotient is $d

;;esac

Sample I/P :1.Addition2.Subraction3.Multiplication4.DivisionEnter your choice:1Enter the value of b:3Enter the value of c:4

 b is 3 c is 4

the sum is 7Sample O/P:

 b is 3 c is 4the sum is 7

Result :Thus the shell program to perform arithmetic operations using case is executed and output isverified successfully.

Ex. No:3(a) ROUND ROBIN SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such asRound Robin Scheduling.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 14/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

14

Algorithm for RR

Step 1: Start the processStep 2: Accept the number of processes in the ready Queue and time quantum (or) timesliceStep 3: For each process in the ready Q, assign the process id and accept the CPU burst

timeStep 4: Calculate the no. of time slices for each process where

 No. of time slice for process(n) = burst t ime process(n)/time sliceStep 5: If the burst time is less than the time slice then the no. of time slices =1.Step 6: Consider the ready queue is a circular Q, calculate

(a) Waiting time for process(n) = waiting time of process(n-1)+ burst time of process(n-1 ) + the time difference in getting the CPU from process(n-1)

(b) Turn around time for process(n) = waiting time of process(n) + burst time of process(n)+ the time difference in getting CPU from process(n).

Step 7: Calculate(a) Average waiting time = Total waiting Time / Number of process(b) Average Turnaround time = Total Turnaround Time / Number of process

Step 8: Stop the process/* ROUND ROBIN SCHEDULING ALGORITHM */

#include<stdio.h>#include<conio.h>void main(){int ts,pid[10],need[10],wt[10],tat[10],i,j,n,n1;int bt[10],flag[10],ttat=0,twt=0;

float awt,atat;clrscr(); printf("\t\t ROUND ROBIN SCHEDULING \n"); printf("Enter the number of Processors \n");scanf("%d",&n);n1=n;

 printf("\n Enter the Timeslice \n");scanf("%d",&ts);for(i=1;i<=n;i++){ printf("\n Enter the process ID %d",i);

scanf("%d",&pid[i]); printf("\n Enter the Burst Time for the process");scanf("%d",&bt[i]);need[i]=bt[i];

}for(i=1;i<=n;i++){flag[i]=1;wt[i]=0;

}while(n!=0)

{for(i=1;i<=n;i++)

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 15/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

15

{if(need[i]>=ts){for(j=1;j<=n;j++){

if((i!=j)&&(flag[i]==1)&&(need[j]!=0))wt[j]+=ts;

}need[i]-=ts;

if(need[i]==0){

flag[i]=0;n--;

}}else

{for(j=1;j<=n;j++){

if((i!=j)&&(flag[i]==1)&&(need[j]!=0))wt[j]+=need[i];

}need[i]=0;n--;flag[i]=0;

}}

}for(i=1;i<=n1;i++){

tat[i]=wt[i]+bt[i];twt=twt+wt[i];ttat=ttat+tat[i];

}awt=(float)twt/n1;atat=(float)ttat/n1;

 printf("\n\n ROUND ROBIN SCHEDULING ALGORITHM \n\n");

 printf("\n\n Process \t Process ID \t BurstTime \t Waiting Time \t TurnaroundTime \n ");for(i=1;i<=n1;i++){ printf("\n %5d \t %5d \t\t %5d \t\t %5d \t\t %5d \n", i,pid[i],bt[i],wt[i],tat[i]);

} printf("\n The average Waiting Time=4.2f",awt); printf("\n The average Turn around Time=4.2f",atat);getch();}

OUTPUT:

ROUND ROBIN SCHEDULING

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 16/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

16

Enter the number of Processors4

Enter the Timeslice5

Enter the process ID 1 5

Enter the Burst Time for the process 10

Enter the process ID 2 6

Enter the Burst Time for the process 15

Enter the process ID 3 7

Enter the Burst Time for the process 20

Enter the process ID 4 8

Enter the Burst Time for the process 25

ROUND ROBIN SCHEDULING ALGORITHM

Process Process ID BurstTime Waiting Time TurnaroundTime

1 5 10 15 25

2 6 15 25 40

3 7 20 25 45

4 8 25 20 45

The average Waiting Time=4.2fThe average Turn around Time=4.2f

Ex. No: 3(b) SJF SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such asSJF Scheduling .

Algorithm for SJF

Step 1: Start the processStep 2: Accept the number of processes in the ready QueueStep 3: For each process in the ready Q, assign the process id and accept the CPU bursttime

Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowestto

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 17/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

17

highest burst time.Step 5: Set the waiting time of the first process as „0‟ and its turnaround time as its bursttime.Step 6: For each process in the ready queue, calculate

(a) Waiting time for process(n)= waiting time of process (n-1) + Burst time of

 process(n-1)(b) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for

 process(n)Step 6: Calculate

(c) Average waiting time = Total waiting Time / Number of process(d) Average Turnaround time = Total Turnaround Time / Number of process

Step 7: Stop the process/* SJF SCHEDULING ALGORITHM */

#include<stdio.h>void main(){

int i,j,k,n,sum,wt[10],tt[10],twt,ttat;int t[10],p[10];float awt,atat;clrscr();

 printf("Enter number of process\n");scanf("%d",&n);

for(i=0;i<n;i++){

 printf("\n Enter the Burst Time of Process %d",i);scanf("\n %d",&t[i]);

}

for(i=0;i<n;i++) p[i]=i;for(i=0;i<n;i++){for(k=i+1;k<n;k++){if(t[i]>t[k])

{ int temp;temp=t[i];t[i]=t[k];t[k]=temp;

temp=p[i]; p[i]=p[k]; p[k]=temp;

}}

 printf("\n\n SHORTEST JOB FIRST SCHEDULING ALGORITHM");

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 18/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

18

 printf("\n PROCESS ID \t BURST TIME \t WAITING TIME \t TURNAROUND TIME\n\n");

wt[0]=0;for(i=0;i<n;i++){

sum=0;for(k=0;k<i;k++){

wt[i]=sum+t[k];sum=wt[i];

}}for(i=0;i<n;i++){tt[i]=t[i]+wt[i];

}

for(i=0;i<n;i++){ printf("%5d \t\t5%d \t\t %5d \t\t %5d \n\n",p[i],t[i],wt[i],tt[i]);}twt=0;ttat=t[0];for(i=1;i<n;i++){

twt=twt+wt[i];ttat=ttat+tt[i];

}awt=(float)twt/n;atat=(float)ttat/n;

 printf("\n AVERAGE WAITING TIME %4.2f",awt); printf("\n AVERAGE TURN AROUND TIME %4.2f",atat);getch();

}}

OUTPUT:

Enter number of process 3

Enter the Burst Time of Process 04Enter the Burst Time of Process 13Enter the Burst Time of Process 25SHORTEST JOB FIRST SCHEDULING ALGORITHMPROCESS ID BURST TIME WAITING TIME TURNAROUND TIME

1 3 0 3

0 4 3 7

2 5 7 12

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 19/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

19

AVERAGE WAITING TIME 3.33AVERAGE TURN AROUND TIME 7.33

Ex. No: 3(c) FCFS SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such asFCFS schedulingAlgorithm for FCFS scheduling:Step 1: Start the processStep 2: Accept the number of processes in the ready QueueStep 3: For each process in the ready Q, assign the process id and accept the CPU bursttimeStep 4: Set the waiting of the first process as „0‟ and its burst time as its turn around timeStep 5: for each process in the Ready Q calculate

(c) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)

(d) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)

Step 6: Calculate(e) Average waiting time = Total waiting Time / Number of process(f)  Average Turnaround time = Total Turnaround Time / Number of process

Step 7: Stop the process

/* FCFS SCHEDULING ALGORITHM */#include<stdio.h>void main(){int i,n,sum,wt,tat,twt,ttat;int t[10];float awt,atat;clrscr();

 printf("Enter number of processors:\n");scanf("%d",&n);for(i=0;i<n;i++){ printf("\n Enter the Burst Time of the process %d",i+1);

scanf("\n %d",&t[i]);} printf("\n\n FIRST COME FIRST SERVE SCHEDULING ALGORITHM \n"); printf("\n Process ID \t Waiting Time \t Turn Around Time \n"); printf("1 \t\t 0 \t\t %d \n",t[0]);sum=0;twt=0;ttat=t[0];for(i=1;i<n;i++){sum+=t[i-1];

wt=sum;tat=sum+t[i];

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 20/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

20

twt=twt+wt;ttat=ttat+tat; printf("\n %d \t\t %d \t\t %d",i+1,wt,tat); printf("\n\n");}

awt=(float)twt/n;atat=(float)ttat/n;

 printf("\n Average Waiting Time %4.2f",awt); printf("\n Average Turnaround Time %4.2f",atat);getch();

}

OUTPUT:

Enter number of processors: 3Enter the Burst Time of the process 1: 2

Enter the Burst Time of the process 2: 5Enter the Burst Time of the process 3: 4

FIRST COME FIRST SERVE SCHEDULING ALGORITHMProcess ID Waiting Time Turn Around Time

1 0 2

2 2 7

3 7 11

Average Waiting Time 3.00Average Turnaround Time 6.67

Ex. No: 3d PRIORITY SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such asPriority Scheduling.

Algorithm for Priority Scheduling:Step 1: Start the processStep 2: Accept the number of processes in the ready Queue

Step 3: For each process in the ready Q, assign the process id and accept the CPU bursttimeStep 4: Sort the ready queue according to the priority number.Step 5: Set the waiting of the first process as „0‟ and its burst time as its turn around timeStep 6: For each process in the Ready Q calculate Waiting time for process(n)= waitingtime of process (n-1) + Burst time of process(n-1)Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)Calculate Average waiting time = Total waiting Time / Number of processAverage Turnaround time = Total Turnaround Time / Number of processStep 7: Stop the processProgram:

/* PRIORITY SCHEDULING */#include <stdio.h>

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 21/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

21

#include <conio.h>void main(){

int i,j,n,tat[10],wt[10],bt[10],pid[10],pr[10],t,twt=0,ttat=0;float awt,atat;

clrscr(); printf("\n-----------PRIORITY SCHEDULING--------------\n"); printf("Enter the No of Process: ");scanf("%d", &n);for (i=0;i<n;i++)

{ pid[i] = i; printf("Enter the Burst time of Pid %d : ",i);scanf("%d",&bt[i]);

 printf("Enter the Priority of Pid %d : ",i);scanf ("%d",&pr[i]);

}// Sorting start

for (i=0;i<n;i++)for(j=i+1;j<n;j++){

if (pr[i] > pr[j] ){

t = pr[i]; pr[i] = pr[j]; pr[j] = t;

t = bt[i]; bt[i] = bt[j]; bt[j] = t;

t = pid[i]; pid[i] = pid[j]; pid[j] = t;

}}

// Sorting finishedtat[0] = bt[0];wt[0] = 0;

for (i=1;i<n;i++){wt[i] = wt[i-1] + bt[i-1];tat[i] = wt[i] + bt[i];}

 printf("\n--------------------------------------------------------------- \n"); printf("Pid\t Priority\tBurst time\t WaitingTime\tTurnArroundTime\n");

 printf("\n--------------------------------------------------------------\n");for(i=0;i<n;i++)

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 22/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

22

{ printf("\n%d\t\t%d\t%d\t\t%d\t\t%d",pid[i],pr[i],bt[i],wt[i],tat[i]);

}for(i=0;i<n;i++)

{

ttat = ttat+tat[i];twt = twt + wt[i];}

awt = (float)twt / n;atat = (float)ttat / n;

 printf("\n\nAvg.Waiting Time: %f\nAvg.Turn Around Time: %f\n",awt,atat);getch();

}OUTPUT:

-----------PRIORITY SCHEDULING--------------Enter the No of Process: 4Enter the Burst time of Pid 0 : 2Enter the Priority of Pid 0 : 3Enter the Burst time of Pid 1 : 6Enter the Priority of Pid 1 : 2Enter the Burst time of Pid 2 : 4Enter the Priority of Pid 2 : 1Enter the Burst time of Pid 3 : 5Enter the Priority of Pid 3 : 7

----------------------------------------------------------------------------------------Pid Priority Burst time WaitingTime TurnArroundTime----------------------------------------------------------------------------------------

2 1 4 0 41 2 6 4 100 3 2 10 123 7 5 12 17

Avg.Waiting Time: 6.500000

Avg.Turn Around Time: 10.750000

Result :

Thus the program to perform various CPU Scheduling algorithms are executed and outputis verified successfully.

Exp no: 4(a) SEQUENTIAL FILE ALLOCATION

AIM: Write a C Program to implement Sequential File Allocation method.

ALGORITHM:Step 1: Start the program.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 23/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

23

Step 2: Get the number of memory partition and their sizes.Step 3: Get the number of processes and values of block size for each process.Step 4: First fit algorithm searches the entire entire memory block until a hole which is

 big enough is encountered. It allocates that memory block for the requesting process.Step 5: Best-fit algorithm searches the memory blocks for the smallest hole which can

 be allocated to requesting process and allocates if.Step 6: Worst fit algorithm searches the memory blocks for the largest hole andallocates it to the process.Step 7: Analyses all the three memory management techniques and display the bestalgorithm which utilizes the memory resources effectively and efficiently.Step 8: Stop the program.

PROGRAM:#include<stdio.h>

#include<conio.h>

main(){

int n,i,j,b[20],sb[20],t[20],x,c[20][20];clrscr();

 printf("Enter no.of files:");scanf("%d",&n);

for(i=0;i<n;i++){

 printf("Enter no. of blocks occupied by file%d",i+1);

scanf("%d",&b[i]);

 printf("Enter the starting block of file%d",i+1);scanf("%d",&sb[i]);t[i]=sb[i];

for(j=0;j<b[i];j++)c[i][j]=sb[i]++;

} printf("Filename\tStart block\tlength\n");for(i=0;i<n;i++)

 printf("%d\t %d \t%d\n",i+1,t[i],b[i]); printf("Enter file name:");

scanf("%d",&x); printf("File name is:%d",x); printf("length is:%d",b[x-1]); printf("blocks occupied:");for(i=0;i<b[x-1];i++)

 printf("%4d",c[x-1][i]);getch();

}OUTPUT:Enter no.of files: 2

Enter no. of blocks occupied by file1 4Enter the starting block of file1 2

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 24/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

24

Enter no. of blocks occupied by file2 10Enter the starting block of file2 5Filename Start block length1 2 4

2 5 10Enter file name: rajeshFile name is:12803 length is:0blocks occupied

Exp no: 4(b) INDEXED FILE ALLOCATION

AIM: Write a C Program to implement Indexed File Allocation method.

Algorithm:

Step 1: Start.Step 2: Let n be the size of the buffer

Step 3: check if there are any producerStep 4: if yes check whether the buffer is fullStep 5: If no the producer item is stored in the bufferStep 6: If the buffer is full the producer has to waitStep 7: Check there is any cosumer.If yes check whether the buffer is emptyStep 8: If no the consumer consumes them from the bufferStep 9: If the buffer is empty, the consumer has to wait.Step 10: Repeat checking for the producer and consumer till requiredStep 11: Terminate the process.

PROGRAM:

#include<stdio.h>#include<conio.h>main(){int n,m[20],i,j,sb[20],s[20],b[20][20],x;clrscr();

 printf("Enter no. of files:");scanf("%d",&n);for(i=0;i<n;i++)

{ printf("Enter starting block and size of file%d:",i+1);scanf("%d%d",&sb[i],&s[i]); printf("Enter blocks occupied by file%d:",i+1);scanf("%d",&m[i]);

 printf("enter blocks of file%d:",i+1);for(j=0;j<m[i];j++)

scanf("%d",&b[i][j]);} printf("\nFile\t index\tlength\n");for(i=0;i<n;i++){

 printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);

}printf("\nEnter file name:");scanf("%d",&x);

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 25/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

25

 printf("file name is:%d\n",x);i=x-1;

 printf("Index is:%d",sb[i]); printf("Block occupied are:");for(j=0;j<m[i];j++)

 printf("%3d",b[i][j]);getch();

}

OUTPUT:

Enter no. of files:2Enter starting block and size of file1: 2 5

Enter blocks occupied by file1:10enter blocks of file1:32 5 4 6 7 2 6 4 7Enter starting block and size of file2: 3 4

Enter blocks occupied by file2:5enter blocks of file2: 2 3 4 5 6File index length1 2 10

2 3 5

Enter file name: venkat

file name is:12803Index is:0Block occupied are:

Exp no:4(c) LINKED FILE ALLOCATION

AIM: Write a C Program to implement Linked File Allocation method.

ALGORITHM:Step 1: Create a queue to hold all pages in memoryStep 2: When the page is required replace the page at the head of the queueStep 3: Now the new page is inserted at the tail of the queueStep 4: Create a stackStep 5: When the page fault occurs replace page present at the bottom of the stack

Step 6: Stop the allocation.

PROGRAM:

#include<stdio.h>

#include<conio.h>struct file{char fname[10];

int start,size,block[10];}f[10];main()

{int i,j,n;

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 26/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

26

clrscr(); printf("Enter no. of files:");scanf("%d",&n);for(i=0;i<n;i++){

 printf("Enter file name:");scanf("%s",&f[i].fname);

 printf("Enter starting block:");scanf("%d",&f[i].start);f[i].block[0]=f[i].start;

 printf("Enter no.of blocks:");scanf("%d",&f[i].size);

 printf("Enter block numbers:");for(j=1;j<=f[i].size;j++){

scanf("%d",&f[i].block[j]);

}}

 printf("File\tstart\tsize\tblock\n");for(i=0;i<n;i++){

 printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);for(j=1;j<=f[i].size-1;j++)

 printf("%d--->",f[i].block[j]); printf("%d",f[i].block[j]); printf("\n");

}getch();

}

OUTPUT:Enter no. of files:2Enter file name:venkatEnter starting block:20

Enter no.of blocks:6Enter block numbers: 412

15453225

Enter file name:rajeshEnter starting block:12Enter no.of blocks:5

Enter block numbers:65

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 27/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

27

432File start size blockvenkat 20 6 4--->12--->15--->45--->32--->25rajesh 12 5 6--->5--->4--->3--->2

Result:

Thus the program for various Memory Allocation Techniques has been implementedsuccessfully.

Ex. No. 5 SemaphoresAIM: To implement producer/consumer problem using semaphore.Algorithm:1 Declare variable for producer & consumer as pthread-t-tid produce tid consume.

2 Declare a structure to add items, semaphore variable set as struct.3 Read number of items to be produced and consumed.4 Declare and define semaphore function for creation and destroy.5 Define producer function.6 Define consumer function.7 Call producer and consumer.8 Stop the execution.

Program#include<stdio.h>#include<semaphore.h>#include<pthread.h>#define NBUFF 10int nitems;struct{int buff[NBUFF];sem_t mutex,nempty,nstored;

}shared;void *produce(void*);void *consume(void*);int main(int argc,char**argv){

 pthread_t tid_produce,tid_consume;if(argc!=2){

 printf("usage:filename<nitems>");return 0;}

 printf("\n\nproducer_consumer problem using semaphore \n"); printf(".......................................................................................\n"); nitems=atoi(argv[1]);sem_init(&shared.mutex,0,1);sem_init(&shared.nempty,0,NBUFF);

sem_init(&shared.nstored,0,0);

 pthread_setconcurrency(2);

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 28/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

28

 pthread_create(&tid_produce,NULL,produce,NULL); pthread_create(&tid_consume,NULL,consume,NULL); pthread_join(tid_produce,NULL); pthread_join(tid_consume,NULL);sem_destroy(&shared.mutex);sem_destroy(&shared.nempty);

sem_destroy(&shared.nstored);}void *produce(void *arg){int i;

for(i=0;i<nitems;i++){sem_wait(&shared.nempty);sem_wait(&shared.mutex);shared.buff[i%NBUFF]=i;

 printf("\tproducer........"); printf("buff[%d]=%d\n\n",i,shared.buff[i%NBUFF]);sem_post(&shared.mutex); sem_post(&shared.nstored);

sleep(3);}return NULL;}

void *consume(void *arg){int i;for(i=0;i<nitems;i++)

{sem_wait(&shared.nstored);

sem_wait(&shared.mutex); printf("\tconsumer............."); printf("buff[%d]=%d\n\n\n",i,shared.buff[i%NBUFF]);sem_post(&shared.mutex);sem_post(&shared.nempty);

sleep(3);}return NULL;S }

Output:Enter the value of n=4

Enter the item=1Enter the item=2Enter the item=3Enter the item=5Consumer item=1Consumer item=2Consumer item=3Consumer item=5Result: Thus the producer consumer program was executed and verified successfully

Ex. No.6 (a) FILE ORGANIZATION TECHNIQUE –  Single- Level Directory

Aim: To implement File Organization Techniques like Single level Directory.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 29/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

29

Algorithm:

1. Initialize values gd =DETECT,gm,count,I,j,mid,cir_x,fname[10][20];2..Read number of files in count.3. Read file name in the loop.4. calculate the mid value

5. Insert the file in the root directory.6. Continue the step 5 until count =07.Stop the execution.

Program:#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<graphics.h>Void main(){

int gd=DETECT,gm,count,I,j,mid,cir_x;char fname[10][20];clrscr();initgraph(&gd,&gm,”c:\\tc\\ bgi”); 

cleardevice();setbkcolor(Green); puts(“Enter no of files do u have?”); scanf(“%d”,&count); for(i=0;i<count;i++){Cleardevice();setbkcolor(Green);

Printf(“Enter file %d name”,i+1); Scanf(“%s”,fname[i]); Setfilstyle(1,MAGENTA);Mid=640/count;Cir_x=mid/3;Bar3d(270,100,370,150,0,0);Settextstyle(2,0,4);Settextjustify(1,1);Outtextxy(320,125,”Root Directory”);setcolor(BLUE); For(j=0;j<=I;j++,cir_x+=mid)

{Line(320,150,cir_x,250);Fillellipse(cir_x,250,30,30);Outtextxy(cir_x,250,fname[j]);

}getch();

}}OUTPUT:

Enter no of files do uhave?3

Enter file 1 name:1.c

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 30/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

30

Enter file 2 name:2.c

Enter file 3 name:3.c

Result: Thus the program to implement File Organization Technique - Single level directory was executed and verified successfully 

Ex. No.6 (b) FILE ORGANIZATION TECHNIQUE –  Two Level Directory

Aim: To implement File Organization Technique - Two level directoryAlgorithm:

1. Initialize values gd =DETECT,gm,count,I,j,mid,cir_x,fname[10][20];2..Read number of files in count.3. Read file name in the loop.4. calculate the mid value5. Insert the file in the root directory.6. Continue the step 5 until count =07.Stop the execution.

Program:#include<stdio.h>

main(){

int nod,file[30][30],nof[10],i,j; printf("\nEnter the numner of directory under root:\t");scanf("%d",&nod);for(i=0;i<nod;i++){

 printf("Enter directory-%d name:\t",i+1);scanf("%d",&file[i][0]);

 printf("Enter number of files in the direcotyr:%d",i+1);scanf("%d",&nof[i]);for(j=1;j<nof;j++)

ROOT

ROOT

ROOT

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 31/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

31

{ printf("Enter the file-%d name:\t",j);scanf("%d",&file[i][j]);

}}

 printf("Two level file organization"); printf("ROOT");for(i=0;i<nod;i++)

 printf("\t\t%d\n",file[i][0]); printf("\n");for(i=0;ii<nod;i++)for(j=1;j<=nof[i];j++)

 printf("\t%d",file[i][j]);}

Result: Thus the program to implement File Organization Technique - Two level directory was executed and verified successfully 

Ex. No.6 (c) FILE ORGANIZATION TECHNIQUE – Hierarchical Directory

Aim: To implement various File Organization Technique  –  Hierarchical directory

Algorithm:1.  Read number of files in count.2.  Read file name in the loop.3.  calculate the mid value4.  Insert the file in the root directory.

5.  Continue the step 5 until count =06.  Stop the execution.

Program:

#include<stdio.h>main(){

int n,nod,dir[20],nof,file[20],i,m,f;a:

 printf("If the current directory has subdir, Press !");scanf("%d",&n);

if(n==1){

 printf("Enter the number of directory");scanf("%d",&nod);for(i=0;i<nod;i++){

 printf("Enter the directory-%d name:\t",i+1);scanf("%d",&dir[i]);

}}

 printf("If the current directory has subdir, Press 2");scanf("%d",&f);if(f==2)

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 32/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

32

{ printf("Enter the number of files:");scanf("%d",&nof);for(i=0;i<nof;i++){

 printf("Enter file-%d name",i+1);scanf("%d",&file[i]);

}}for(i=0;i<nod;i++)

 printf("\t%d",dir[i]);for(i=0;i<nof;i++)

 printf("\t%d",file[i]); printf("Do you want to enter next level? Y-1/N-2");scanf("%d",&m);if(m==1)

goto a;}

Result: Thus the program to implement File Organization Technique - Hierarchical directory wasexecuted and verified successfully 

Ex. No: 7 BANKER’S ALGORITHM 

AIM:  To implement deadlock avoidance & Prevention by using Banker‟s Algorithm.

Deadlock avoidance & Dead Lock Prevention

Banker’s Algorithm: 

When a new process enters a system, it must declare the maximum number ofinstances of each resource type it needed. This number may exceed the total number ofresources in the system. When the user request a set of resources, the system mustdetermine whether the allocation of each resources will leave the system in safe state. Ifit will the resources are allocation; otherwise the process must wait until some other

 process release the resources.

Data structures

  n-Number of process, m-number of resource types.

  Available: Available[j]=k, k –  instance of resource type Rj is available.

  Max: If max[i, j]=k, Pi may request at most k instances resource Rj.

  Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj

   Need: If Need[I, j]=k, Pi may need k more instances of resource type Rj, Need[I, j]=Max[I, j]-Allocation[I, j];

Safety Algorithm

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 33/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

33

1.  Work and Finish be the vector of length m and n respectively, Work=Availableand Finish[i] =False.

2.  Find an i such that both

  Finish[i] =False

   Need<=Work

If no such I exists go to step 4.3.  work=work+Allocation, Finish[i] =True;4.  if Finish[1]=True for all I, then the system is in safe state.

Resource request algorithmLet Request i be request vector for the process Pi, If request i=[j]=k, then

 process Pi wants k instances of resource type Rj.1.  if Request<=Need I go to step 2. Otherwise raise an error condition.2.  if Request<=Available go to step 3. Otherwise Pi must since the resources are

available.

3.  Have the system pretend to have allocated the requested resources to process Pi by modifying the state as follows;Available=Available-Request I;Allocation I =Allocation+Request I;

 Need i=Need i-Request I;If the resulting resource allocation state is safe, the transaction is completed and processPi is allocated its resources. However if the state is unsafe, the Pi must wait for Requesti and the old resource-allocation state is restored.

ALGORITHM:

1.  Start the program.2.  Get the values of resources and processes.3.  Get the avail value.4.  After allocation find the need value.5.  Check whether its possible to allocate.6.  If it is possible then the system is in safe state.7.  Else system is not in safety state.8.  If the new request comes then check that the system is in safety.9.  or not if we allow the request.10. stop the program.

/* BANKER‟S ALGORITHM */ Program:#include<stdio.h>#include<conio.h>struct da{

int max[10],a1[10],need[10],before[10],after[10];}p[10];void main(){

int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0;clrscr();

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 34/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

34

 printf("\n ENTER THE NO. OF PROCESSES:");scanf("%d",&n);

 printf("\n ENTER THE NO. OF RESOURCES:");scanf("%d",&r);for(i=0;i<n;i++)

{ printf("PROCESS %d \n",i+1);for(j=0;j<r;j++){ printf("MAXIMUM VALUE FOR RESOURCE %d:",j+1);scanf("%d",&p[i].max[j]);}

for(j=0;j<r;j++){ printf("ALLOCATED FROM RESOURCE %d:",j+1);scanf("%d",&p[i].a1[j]);

 p[i].need[j]=p[i].max[j]-p[i].a1[j];}

}for(i=0;i<r;i++){ printf("ENTER TOTAL VALUE OF RESOURCE %d:",i+1);scanf("%d",&tot[i]);

}for(i=0;i<r;i++){

for(j=0;j<n;j++)temp=temp+p[j].a1[i];av[i]=tot[i]-temp;temp=0;

} printf("\n\t RESOURCES ALLOCATED NEEDED TOTAL AVAIL");for(i=0;i<n;i++){ printf("\n P%d \t",i+1);for(j=0;j<r;j++)

 printf("%d",p[i].max[j]);

 printf("\t");for(j=0;j<r;j++) printf("%d",p[i].a1[j]); printf("\t");for(j=0;j<r;j++)

 printf("%d",p[i].need[j]); printf("\t");for(j=0;j<r;j++){

if(i==0) printf("%d",tot[j]);

} printf(" ");

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 35/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

35

for(j=0;j<r;j++){

if(i==0) printf("%d",av[j]);

}

} printf("\n\n\t AVAIL BEFORE\T AVAIL AFTER ");for(l=0;l<n;l++){for(i=0;i<n;i++){

for(j=0;j<r;j++){if(p[i].need[j] >av[j])cn++;if(p[i].max[j]==0)

cz++;}

if(cn==0 && cz!=r){

for(j=0;j<r;j++){

 p[i].before[j]=av[j]-p[i].need[j]; p[i].after[j]=p[i].before[j]+p[i].max[j];av[j]=p[i].after[j];

 p[i].max[j]=0;}

 printf("\n P %d \t",i+1);for(j=0;j<r;j++)

 printf("%d",p[i].before[j]); printf("\t");for(j=0;j<r;j++)

 printf("%d",p[i].after[j]);cn=0;cz=0;c++;

 break;

}else{cn=0;cz=0;

}}

}if(c==n)

 printf("\n THE ABOVE SEQUENCE IS A SAFE SEQUENCE");else

 printf("\n DEADLOCK OCCURED");

getch();}

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 36/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

36

OUTPUT:

//TEST CASE 1:

ENTER THE NO. OF PROCESSES:4

ENTER THE NO. OF RESOURCES:3PROCESS 1MAXIMUM VALUE FOR RESOURCE 1:3MAXIMUM VALUE FOR RESOURCE 2:2MAXIMUM VALUE FOR RESOURCE 3:2ALLOCATED FROM RESOURCE 1:1ALLOCATED FROM RESOURCE 2:0ALLOCATED FROM RESOURCE 3:0PROCESS 2

MAXIMUM VALUE FOR RESOURCE 1:6MAXIMUM VALUE FOR RESOURCE 2:1MAXIMUM VALUE FOR RESOURCE 3:3ALLOCATED FROM RESOURCE 1:5ALLOCATED FROM RESOURCE 2:1ALLOCATED FROM RESOURCE 3:1PROCESS 3MAXIMUM VALUE FOR RESOURCE 1:3MAXIMUM VALUE FOR RESOURCE 2:1MAXIMUM VALUE FOR RESOURCE 3:4ALLOCATED FROM RESOURCE 1:2ALLOCATED FROM RESOURCE 2:1ALLOCATED FROM RESOURCE 3:1PROCESS 4MAXIMUM VALUE FOR RESOURCE 1:4MAXIMUM VALUE FOR RESOURCE 2:2MAXIMUM VALUE FOR RESOURCE 3:2ALLOCATED FROM RESOURCE 1:0ALLOCATED FROM RESOURCE 2:0ALLOCATED FROM RESOURCE 3:2ENTER TOTAL VALUE OF RESOURCE 1:9

ENTER TOTAL VALUE OF RESOURCE 2:3ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAILP1 322 100 222 936 112P2 613 511 102P3 314 211 103P4 422 002 420

AVAIL BEFORE AVAIL AFTERP 2 010 623

P 1 401 723P 3 620 934

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 37/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

37

P 4 514 936THE ABOVE SEQUENCE IS A SAFE SEQUENCE

//TEST CASE:2

ENTER THE NO. OF PROCESSES:4ENTER THE NO. OF RESOURCES:3

PROCESS 1MAXIMUM VALUE FOR RESOURCE 1:3MAXIMUM VALUE FOR RESOURCE 2:2MAXIMUM VALUE FOR RESOURCE 3:2ALLOCATED FROM RESOURCE 1:1ALLOCATED FROM RESOURCE 2:0ALLOCATED FROM RESOURCE 3:1PROCESS 2

MAXIMUM VALUE FOR RESOURCE 1:6MAXIMUM VALUE FOR RESOURCE 2:1MAXIMUM VALUE FOR RESOURCE 3:3ALLOCATED FROM RESOURCE 1:5ALLOCATED FROM RESOURCE 2:1ALLOCATED FROM RESOURCE 3:1PROCESS 3MAXIMUM VALUE FOR RESOURCE 1:3MAXIMUM VALUE FOR RESOURCE 2:1MAXIMUM VALUE FOR RESOURCE 3:4ALLOCATED FROM RESOURCE 1:2ALLOCATED FROM RESOURCE 2:1ALLOCATED FROM RESOURCE 3:2PROCESS 4MAXIMUM VALUE FOR RESOURCE 1:4MAXIMUM VALUE FOR RESOURCE 2:2MAXIMUM VALUE FOR RESOURCE 3:2ALLOCATED FROM RESOURCE 1:0ALLOCATED FROM RESOURCE 2:0ALLOCATED FROM RESOURCE 3:2ENTER TOTAL VALUE OF RESOURCE 1:9

ENTER TOTAL VALUE OF RESOURCE 2:3ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAILP1 322 101 221 936 110P2 613 511 102P3 314 212 102P4 422 002 420

AVAIL BEFORE AVAIL AFTERDEADLOCK OCCURED

Ex.No.: 8 Dead Lock Detection

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 38/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

38

AIM: To Implement DeadLock Detection Algorithm using C

ALGORITHM:

1.  Start the program.

2.  Get the values of resources and processes.3.  Get the avail value.4.  After allocation find the need value.5.  Check whether its possible to allocate.6.  If it is possible then the system is in safe state.7.  Else system is not in safety state.8.  If the new request comes then check that the system is in safety.9.  or not if we allow the request.10. stop the program.

Program:#include&lt;stdio.h&gt;#include&lt;conio.h&gt;void main(){int found,flag,l,p[4][5],tp,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;clrscr();

 printf("enter total no of processes");scanf("%d",&amp;tp);

 printf("enter clain matrix");for(i=1;i&lt;=4;i++)

for(j=1;j&lt;=5;j++){scanf("%d",&amp;c[i][j]);}

 printf("enter allocation matrix");for(i=1;i&lt;=4;i++)for(j=1;j&lt;=5;j++){scanf("%d",&amp;p[i][j]);}

 printf("enter resource vector:\n");

for(i=1;i&lt;=5;i++){scanf("%d",&amp;r[i]);}

 printf("enter availability vector:\n");for(i=1;i&lt;=5;i++){scanf("%d",&amp;a[i]);temp[i]=a[i];}

for(i=1;i&lt;=4;i++){

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 39/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

39

sum=0;for(j=1;j&lt;=5;j++){sum+=p[i][j];}

if(sum==0){m[k]=i;k++;}}for(i=1;i&lt;=4;i++){for(l=1;l&lt;k;l++)if(i!=m[l]){

flag=1;for(j=1;j&lt;=5;j++)if(c[i][j]&gt;temp[j]){flag=0;

 break;}}if(flag==1){m[k]=i;k++;for(j=1;j&lt;=5;j++)temp[j]+=p[i][j];}}

 printf("deadlock causing processes are:");for(j=1;j&lt;=tp;j++){found=0;for(i=1;i&lt;k;i++)

{if(j==m[i])found=1;}if(found==0)

 printf("%d\t",j);}getch();}

INPUT:

enter total no. of processes : 4enter claim matrix :

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 40/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

40

0 1 0 0 10 0 1 0 10 0 0 0 11 0 1 0 1enter allocation matrix :

1 0 1 1 01 1 0 0 00 0 0 1 00 0 0 0 0enter resource vector :2 1 1 2 1enter the availability vector :0 0 0 0 1

OUTPUT :

deadlock causing processes are : 1 2

Ex. No: 9 a) FIFO PAGE REPLACEMENT ALGORITHM

AIM: To implement page replacement algorithms FIFO (First In First Out)

ALGORITHM:Step 1: Create a queue to hold all pages in memoryStep 2: When the page is required replace the page at the head of the queueStep 3: Now the new page is inserted at the tail of the queue

/* FIFO Page Replacement Algorithm */Program:

#include<stdio.h>#include<conio.h>int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;void main(){clrscr();

 printf("\n \t\t\t FIFI PAGE REPLACEMENT ALGORITHM"); printf("\n Enter no.of frames....");

scanf("%d",&nof); printf("Enter number of reference string..\n");scanf("%d",&nor);

 printf("\n Enter the reference string..");for(i=0;i<nor;i++)scanf("%d",&ref[i]);

 printf("\nThe given reference string:");for(i=0;i<nor;i++)

 printf("%4d",ref[i]);for(i=1;i<=nof;i++)frm[i]=-1;

 printf("\n");

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 41/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

41

for(i=0;i<nor;i++){

flag=0; printf("\n\t Reference np%d->\t",ref[i]);for(j=0;j<nof;j++)

{if(frm[j]==ref[i]){flag=1;

 break;}}if(flag==0)

{ pf++;victim++;victim=victim%nof;

frm[victim]=ref[i];for(j=0;j<nof;j++)

 printf("%4d",frm[j]);}

} printf("\n\n\t\t No.of pages faults...%d",pf);getch();

}

OUTPUT:

FIFO PAGE REPLACEMENT ALGORITHM

Enter no.of frames....4Enter number of reference string..6

Enter the reference string..5 6 4 1 2 3

The given reference string:...................................... 5 6 4 1 2 3

Reference np5-> 5 -1 -1 -1Reference np6-> 5 6 -1 -1Reference np4-> 5 6 4 -1Reference np1-> 5 6 4 1Reference np2-> 2 6 4 1Reference np3-> 2 3 4 1

No.of pages faults...6

Ex. No:9(b) LRU PAGE REPLACEMENT ALGORITHM

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 42/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

42

AIM: To implement page replacement algorithm LRU (Least Recently Used)

LRU (Lease Recently Used)Here we select the page that has not been used for the longest period of time.

ALGORITHM:Step 1: Create a queue to hold all pages in memoryStep 2: When the page is required replace the page at the head of the queueStep 3: Now the new page is inserted at the tail of the queueStep 4: Create a stackStep 5: When the page fault occurs replace page present at the bottom of the stack

/* LRU Page Replacement Algorithm */

Program:#include<stdio.h>

#include<conio.h>int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;int recent[10],lrucal[50],count=0;int lruvictim();

void main(){

clrscr(); printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM"); printf("\n Enter no.of Frames....");scanf("%d",&nof);

 printf(" Enter no.of reference string..");scanf("%d",&nor);

 printf("\n Enter reference string..");for(i=0;i<nor;i++)scanf("%d",&ref[i]);

 printf("\n\n\t\t LRU PAGE REPLACEMENT ALGORITHM "); printf("\n\t The given reference string:"); printf("\n……………………………….."); 

for(i=0;i<nor;i++) printf("%4d",ref[i]);for(i=1;i<=nof;i++){frm[i]=-1;lrucal[i]=0;

}

for(i=0;i<10;i++)recent[i]=0;

 printf("\n");for(i=0;i<nor;i++){

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 43/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

43

flag=0; printf("\n\t Reference NO %d->\t",ref[i]);for(j=0;j<nof;j++){

if(frm[j]==ref[i])

{flag=1;

 break;}

}if(flag==0){count++;if(count<=nof)victim++;else

victim=lruvictim(); pf++;frm[victim]=ref[i];for(j=0;j<nof;j++)

 printf("%4d",frm[j]);}recent[ref[i]]=i;

} printf("\n\n\t No.of page faults...%d",pf);getch();

}int lruvictim(){

int i,j,temp1,temp2;for(i=0;i<nof;i++){temp1=frm[i];lrucal[i]=recent[temp1];

}temp2=lrucal[0];for(j=1;j<nof;j++)

{if(temp2>lrucal[j])temp2=lrucal[j];

}for(i=0;i<nof;i++)if(ref[temp2]==frm[i])return i;return 0;

}

OUTPUT

LRU PAGE REPLACEMENT ALGORITHM

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 44/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

44

Enter no.of Frames....3Enter no.of reference string..6

Enter reference string..6 5 4 2 3 1

LRU PAGE REPLACEMENT ALGORITHMThe given reference string:…………………. 6 5 4 2 3 1 

Reference NO 6-> 6 -1 -1Reference NO 5-> 6 5 -1Reference NO 4-> 6 5 4Reference NO 2-> 2 5 4Reference NO 3-> 2 3 4Reference NO 1-> 2 3 1

 No.of page faults...6

Ex. No: 9(c) OPTIMAL(LFU) PAGE REPLACEMENT ALGORITHM

AIM:  To implement page replacement algorithmsOptimal (The page which is not used for longest time)

ALGORITHM:Optimal algorithm

Here we select the page that will not be used for the longest period of time.OPTIMAL:Step 1: Create a arrayStep 2: When the page fault occurs replace page that will not be used for the longest periodof time

/*OPTIMAL(LFU) page replacement algorithm*/

Program#include<stdio.h>#include<conio.h>int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;

int recent[10],optcal[50],count=0;int optvictim();void main(){

clrscr(); printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHN"); printf("\n................................."); printf("\nEnter the no.of frames");scanf("%d",&nof);

 printf("Enter the no.of reference string");scanf("%d",&nor);

 printf("Enter the reference string");for(i=0;i<nor;i++)

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 45/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

45

scanf("%d",&ref[i]);clrscr();

 printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM"); printf("\n................................"); printf("\nThe given string");

 printf("\n....................\n");for(i=0;i<nor;i++)

 printf("%4d",ref[i]);for(i=0;i<nof;i++){

frm[i]=-1;optcal[i]=0;

}for(i=0;i<10;i++)

recent[i]=0; printf("\n");

for(i=0;i<nor;i++){

flag=0; printf("\n\tref no %d ->\t",ref[i]);for(j=0;j<nof;j++){

if(frm[j]==ref[i]){

flag=1; break;

}}if(flag==0){

count++;if(count<=nof)

victim++;else

victim=optvictim(i); pf++;frm[victim]=ref[i];

for(j=0;j<nof;j++) printf("%4d",frm[j]);}

} printf("\n Number of page faults: %d",pf);getch();

}int optvictim(int index){

int i,j,temp,notfound;for(i=0;i<nof;i++)

{notfound=1;

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 46/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

46

for(j=index;j<nor;j++)if(frm[i]==ref[j]){

notfound=0;optcal[i]=j;

 break;}

if(notfound==1)return i;

}temp=optcal[0];for(i=1;i<nof;i++)

if(temp<optcal[i])temp=optcal[i];

for(i=0;i<nof;i++)if(frm[temp]==frm[i])

return i;return 0;

}

OUTPUT:

OPTIMAL PAGE REPLACEMENT ALGORITHM

Enter no.of Frames....3Enter no.of reference string..6

Enter reference string..6 5 4 2 3 1

OPTIMAL PAGE REPLACEMENT ALGORITHMThe given reference string:…………………. 6 5 4 2 3 1 

Reference NO 6-> 6 -1 -1Reference NO 5-> 6 5 -1Reference NO 4-> 6 5 4

Reference NO 2-> 2 5 4Reference NO 3-> 2 3 4Reference NO 1-> 2 3 1

 No.of page faults...6

Ex. No: 10DEVELOPING APPLICATION USING INTER PROCESS COMMUNICATION -Pipes

and Shared memory

Aim:

To write a C program to implement inter process communication using pipes and sharedmemory.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 47/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

47

IPC using Shared Memory

Algorithm:

1.  Call the fork () system call.

2.  If (!child) then input the shared memory address and create the IPC using shmget ().3.  Then the parent is writing on to the address.4.  Else then input the address using shmget()5.  Assign the shared memory id.6.  Then the child is reading the same content.

IPC - Pipe

Conceptually a pipe can be thought of much like a hose-pipe, in that it is a conduitwhere we pour data in at one end and it flows out at the other. A pipe looks a lot like a file in thatit is treated as a sequential data stream. Unlike a file, a pipe has two ends, so when we create a

 pipe we get two end points back in return. We can write to one end point and read from the other.Also unlike a file, there is no physical storage of data when we close a pipe, anything that waswritten in one end but not read out from the other end will be lost.

We can illustrate the use of pipes as conduits between processes in the following diagram:

Here we see two processes which I've called Parent and Child, for reasons that will becomeapparent shortly. The Parent can write to Pipe A. and read from Pipe B. The Child can read fromPipe A and write to Pipe B.

Algorithm:1 Start the program.2 Declare the file pointer fp, f1, f2.3 Read the choice.

4 In case „1‟ open a file and display the list of files and directories.5 In case „2‟ open a file and ptr bin\pwd for read mode it displays the personnel

working directory.6 In case „3‟ open a file in write mode.7 In case „4‟ Exit command is execute.8 Stop the program.

Program#include<stdio.h>main(int argc,char * argv[]){

int p1[2],p2[2],p3[2],p4[2];int pid1,pid2,pid3,pid4;

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 48/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

48

int wc,cc,sc,lc,j,ch_id,status,count;char c;FILE *fp;wc=sc=cc=lc=0;

 pipe(p1);

 pipe(p2); pipe(p3); pipe(p4); pid1=fork();if(pid1==0){fp=fopen(argv[1],"r");while((c=getc(fp))!=EOF)cc++;write(p1[1],&cc,sizeof(int));fclose(fp);

exit(0);}

 pid2=fork();f(pid2==0)

{

fp=fopen(argv[1],"r");while((c=getc(fp))!=EOF)if(c=='\n')lc++;write(p2[1],&lc,sizeof(int));fclose(fp);exit(0);

} pid3=fork();if(pid3==0){fp=fopen(argv[1],"r");while((c=getc(fp))!=EOF)if(c=='.')

sc++;write(p3[1],&sc,sizeof(int));fclose(fp);exit(0);

} pid4=fork();if(pid4==0){fp=fopen(argv[1],"r");while((c=getc(fp))!=EOF){

if(c==' '|c=='\n')wc++;

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 49/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

49

}write(p4[1],&wc,sizeof(int));fclose(fp);exit(0);

}

 j=0;while(j<4){ch_id=wait(&status);if(ch_id==pid1){

read(p1[0],&count,sizeof(int)); printf("\n\n CHARACTER COUNT:%d",count);

}if(ch_id==pid2){

read(p2[0],&count,sizeof(int)); printf("\n\n LINE COUNT:%d",count);}

if(ch_id==pid3){read(p3[0],&count,sizeof(int));

 printf("\n\n SENTENCE COUNT:%d",count);}

if(ch_id==pid4){read(p4[0],&count,sizeof(int));

 printf("\n\nWORD COUNT:%d",count);}

 j++;}

}

Output:

CHARACTER COUNT: 60

LINE COUNT: 6

SENTENCE COUNT: 8

WORD COUNT: 20

Result:

Thus the Inter process communication has been implemented successfully using sharedmemory and pipes.

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 50/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

50

Ex. No: 11 PAGING

Aim:  To implement the Memory management policy- Paging.

Algorithm:

Step 1: Read all the necessary input from the keyboard.Step 2: Pages - Logical memory is broken into fixed - sized blocks.Step 3: Frames –  Physical memory is broken into fixed –  sized blocks.Step 4: Calculate the physical address using the following

Physical address = ( Frame number * Frame size ) + offsetStep 5: Display the physical address.Step 6: Stop the process.

/* Memory Allocation with Paging Technique */

Program:

#include <stdio.h>#include <conio.h>struct pstruct{

int fno;int pbit;

}ptable[10];

int pmsize,lmsize,psize,frame,page,ftable[20],frameno;

void info(){

 printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n"); printf("\n\nEnter the Size of Physical memory: ");scanf("%d",&pmsize);

 printf("\n\nEnter the size of Logical memory: ");scanf("%d",&lmsize);

 printf("\n\nEnter the partition size: ");scanf("%d",&psize);frame = (int) pmsize/psize;

 page = (int) lmsize/psize; printf("\nThe physical memory is divided into %d no.of frames\n",frame); printf("\nThe Logical memory is divided into %d no.of pages",page);

}

void assign(){

int i;for (i=0;i<page;i++){

 ptable[i].fno = -1;

 ptable[i].pbit= -1;}

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 51/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

51

for(i=0; i<frame;i++)ftable[i] = 32555;

for (i=0;i<page;i++){

 printf("\n\nEnter the Frame number where page %d must be placed: ",i);

scanf("%d",&frameno);ftable[frameno] = i;if(ptable[i].pbit == -1){

 ptable[i].fno = frameno; ptable[i].pbit = 1;

}}getch();

// clrscr(); printf("\n\nPAGE TABLE\n\n");

 printf("PageAddress FrameNo. PresenceBit\n\n");for (i=0;i<page;i++)

 printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit); printf("\n\n\n\tFRAME TABLE\n\n"); printf("FrameAddress PageNo\n\n");for(i=0;i<frame;i++)

 printf("%d\t\t%d\n",i,ftable[i]);}void cphyaddr(){

int laddr,paddr,disp,phyaddr,baddr;getch();

// clrscr(); printf("\n\n\n\tProcess to create the Physical Address\n\n"); printf("\nEnter the Base Address: ");scanf("%d",&baddr);

 printf("\nEnter theLogical Address: ");scanf("%d",&laddr);

 paddr = laddr / psize;disp = laddr % psize;

if(ptable[paddr].pbit == 1 ) phyaddr = baddr + (ptable[paddr].fno*psize) + disp; printf("\nThe Physical Address where the instruction present: %d",phyaddr);

}void main(){

clrscr();info();assign();cphyaddr();getch();

}OUTPUT:

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 52/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

52

MEMORY MANAGEMENT USING PAGINGEnter the Size of Physical memory: 16

Enter the size of Logical memory: 8

Enter the partition size: 2

The physical memory is divided into 8 no.of frames

The Logical memory is divided into 4 no.of pages

Enter the Frame number where page 0 must be placed: 5

Enter the Frame number where page 1 must be placed: 6

Enter the Frame number where page 2 must be placed: 7

Enter the Frame number where page 3 must be placed: 2

PAGE TABLE

PageAddress FrameNo. PresenceBit

0 5 11 6 12 7 13 2 1

FRAME TABLEFrameAddress PageNo

0 325551 325552 33 325554 32555

5 06 17 2

Process to create the Physical AddressEnter the Base Address: 1000Enter theLogical Address: 3

The Physical Address where the instruction present: 1013

Result:

Thus the program for Paging has been implemented successfully

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 53/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

53

Ex.No.12 Implementation of Threading & Synchronization

ApplicationsAim:

Program:

#include<stdio.h>

#include<semaphore.h>#include<pthread.h>

#define N 5#define THINKING 0#define HUNGRY 1#define EATING 2#define LEFT (ph_num+4)%N#define RIGHT (ph_num+1)%N

sem_t mutex;sem_t S[N];

void * philospher(void *num);void take_fork(int);void put_fork(int);void test(int);

int state[N];int phil_num[N]={0,1,2,3,4};

int main(){int i;

 pthread_t thread_id[N];sem_init(&mutex,0,1);for(i=0;i<N;i++)

sem_init(&S[i],0,0);for(i=0;i<N;i++){

 pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]); printf("Philosopher %d is thinking\n",i+1);

}for(i=0;i<N;i++)

 pthread_join(thread_id[i],NULL);}

void *philospher(void *num){

while(1){

int *i = num;sleep(1);

take_fork(*i);sleep(0);

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 54/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

54

 put_fork(*i);}

}

void take_fork(int ph_num)

{sem_wait(&mutex);state[ph_num] = HUNGRY;

 printf("Philosopher %d is Hungry\n",ph_num+1);test(ph_num);sem_post(&mutex);sem_wait(&S[ph_num]);sleep(1);

}

void test(int ph_num)

{if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] !=

EATING){

state[ph_num] = EATING;sleep(2);

 printf("Philosopher %d takes fork %d and %d\n",ph_num+1,LEFT+1,ph_num+1); printf("Philosopher %d is Eating\n",ph_num+1);sem_post(&S[ph_num]);

}}

void put_fork(int ph_num){

sem_wait(&mutex);state[ph_num] = THINKING;

 printf("Philosopher %d putting fork %d and %ddown\n",ph_num+1,LEFT+1,ph_num+1);

 printf("Philosopher %d is thinking\n",ph_num+1);test(LEFT);test(RIGHT);

sem_post(&mutex);}

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 55/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

55

CONTENT BEYOND SYLLABUS

IMPLEMENTATION OF MEMORY MANAGEMENT TECHNIQUES-First fit, Best fit

and Worst fit.

MEMORY MANAGEMENT

The purpose of the memory manager is

o  to allocate primary memory space to processeso  to map the process address space into the allocated portion of the primary memoryo  to minimize access times using a cost-effective amount of primary memory

Memory Management Algorithms

In an environment that supports dynamic memory allocation, the memory manager must keep arecord of the usage of each allocatable block of memory. This record could be kept by usingalmost any data structure that implements linked lists. An obvious implementation is to define afree list of block descriptors, with each descriport containing a pointer to the next descriptor, a

 pointer to the block, and the length of the block. The memory manager keeps a free list pointerand inserts entries into the list in some order conducive to its allocation strategy. A number ofstrategies are used to allocate space to the processes that are competing for memory.

o  Best Fit

The allocator places a process in the smallest block of unallocated memory in which it will fit.

Problems: 

  It requires an expensive search of the entire free list to find the best hole.

  More importantly, it leads to the creation of lots of little holes that are not big enough to

satisfy any requests. This situation is called  fragmentation, and is a problem for all memory-management strategies, although it is particularly bad for best-fit.

Solution:One way to avoid making little holes is to give the client a bigger block than it askedfor. For example, we might round all requests up to the next larger multiple of 64 bytes. Thatdoesn't make the fragmentation go away, it just hides it.

  Unusable space in the form of holes is called external fragmentation 

  Unusable space in the form of holes is called external fragmentation

o  Worst Fit

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 56/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

56

The memory manager places process in the largest block of unallocated memory available. Theides is that this placement will create the largest hole after the allocations, thus increasing the

 possibility that, compared to best fit, another process can use the hole created as a result ofexternal fragmentation.

o  First Fit

Another strategy is first fit, which simply scans the free list until a large enough hole is found.Despite the name, first-fit is generally better than best-fit because it leads to less fragmentation.

Aim

To write a c program to implement memory management techniques (first fit, bestfit and worstfit).

Algorithm

1.  Enter the five free memories and five processes.2.  Enter the choice.3.  In first fit, allocate the process to free memory by sequential order if free memorysize>=process size.4.  In best fit, allocate the process to free memory, if the memory size is first, equal to freememory then go for greater memory size.5.  In worst fit, allocate the process to free memory, if the memory size is greater then go forequal memory size.

Sample Output:

[cse98@cselinux ~]$ cc fit.c[cse98@cselinux ~]$ ./a.out

Enter five freememory25 45 65 20 10Enter five processes45 20 95 100 601.First fit2.Best fit3.Worst fit

Enter your choice:1First fit process 20 is allocated for free memory 25 process 45 is allocated for free memory 45 process 60 is allocated for free memory 65 process size 95 is not allocated for any memory process size 100 is not allocated for any memory[cse98@cselinux ~]$[cse98@cselinux ~]$ cc fit.c[cse98@cselinux ~]$ ./a.outEnter five freememory25 45 65 20 10

Enter five processes45 20 95 100 60

7/25/2019 OPERATING SYSTEM LABORATORY MANUAL

http://slidepdf.com/reader/full/operating-system-laboratory-manual 57/57

cseitquestions.blogspot.in | cseitquestions.blogspot.in | cseitquestions.blogspot.in 

1.First fit2.Best fit3.Worst fitEnter your choice:2Best fit

 process 20 is allocated for free memory 20 process 45 is allocated for free memory 45 process 60 is allocated for free memory 65 process size 95 is not allocated for any memory[cse98@cselinux ~]$ cc fit.c[cse98@cselinux ~]$ ./a.outEnter five freememory25 45 65 20 10Enter five processes45 20 95 100 601.First fit

2.Best fit3.Worst fitEnter your choice:3Worst fit

 process 45 is allocated for free memory 65 process 20 is allocated for free memory 45 process size 95 is not allocated for any memory process size 100 is not allocated for any memory process size 60 is not allocated for any memory[cse98@cselinux ~]$

Result:

Thus the program for memory management technique (first fit, best fit and worst fit) has been implemented successfully.