Csit (r22) 2-1 Operating Systems Lab Manual
Csit (r22) 2-1 Operating Systems Lab Manual
LABORATORY MANUAL
(R22A0587)
B. TECH
II YEAR – I SEM
(2024-25)
PREPARED BY
B.ARUNA KUMARI
VISION
To achieve high quality in technical education that provides the skills and
attitude to adapt to the global needs of the Information Technology sector,
through academic and research excellence.
MISSION
To equip the students with the cognizance for problem solving and
toimprove the teaching pedagogy by using innovative techniques.
To promote the necessary moral and ethical values among the engineers,
forthe betterment of the society
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),those
who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) neededin the
lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allottedto you
by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note book,
and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should be
utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab sessions.
Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody found
loitering outside the lab / class without permission during working hours will be treated seriously and
punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is keptproperly.
WEEK-1 Practice File handling utilities, Process utilities, Disk utilities, Networking 20
commands, Filters, Test processing utilities and Backup utilities.
WEEK-2 Write a shell script that receives any number of file names as arguments 29
checks if every argument supplied is a file or directory and reports
accordingly. Whenever the argument is a file it reports no of lines present
in it.
WEEK-3 Simulate the following CPU scheduling algorithms. 31
a)FCFS b) SJF c) Round Robin d) Priority.
WEEK-4 Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers 40
Algorithm for Dead Lock Prevention.
a) Write a C program to simulate the concept of Dining-philosophers 48
WEEK-5 problem.
B) Write a C program to simulate producer-consumer problem using 51
Semaphores
a) Write a program that illustrates communication between two 53
WEEK-6 processes using named pipes or FIFO.
b) Write a C program that receives a message from message queue and 57
display them.
WEEK-7 Write a C program that illustrates two processes communicating using 60
Shared memory
WEEK-8 Simulate all page replacement algorithms 62
a) FIFO b) LRU c) OPTIMAL
WEEK-9 Write a C program that takes one or more file/directory names as 73
command line input and reports following information
a) File Type b) Number Of Links c) Time of last Access d) Read, write
and execute permissions
WEEK-10 Write a C program to simulate disk scheduling algorithms. 75
a) FCFS b) SCAN c) C-SCAN
OPERATING SYSTEMS LAB PAGE 1
To Install Ubuntu Linux – Complete Step by Step
clickforward.
Again SHell
bg Send to background
owner andgroup
loop
dc Desk Calculator
op Operator access
ps Process status
apipe
diskusager
variablereadonly Mark
rm Remove files
ss Socket Statistics
vi Text Editor
whereis Search the user's $path, man pages and source files
for a program
which Search the user's $path for a program
filewhile Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -
un')
wget Retrieve web pages or files via HTTP, HTTPS or
FTPwrite Send a message to another user
x
Step 3: provide login and password (nothing is displayed on screen while typing password)
To Append data into the file: To append data into the same file use append operator >> to write
intothefile, else the file will be overwritten (i.e., all of its contents will be erased).
cat >> file1.txt
The above cat command will concatenate the two files (file1.txt and file2.txt) and it will display
the output in the screen. Some times the output may not fit the monitor screen. In such situation
you canprint those files in a new file or display the file using less command.
cat file1.txt file2.txt | less
To remove more files at once: rm command removes file1.txt and file2.txt files at
thesame time.rm file1.txt file2.txt
cd linux-command
This command will take you to the sub-directory(linux-command) from its parent directory.
Ex:
cd ..
This will change to the parent-directory from the current working directory/sub-directory.
cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into
thedirectory (thedirectory is not overwritten).
ls COMMAND:
ls command lists the files and directories under current working directory. Display
rootdirectorycontents:
ls /
lists the contents of root directory.
Display hidden files and
directories:ls -a
lists all entries including hidden files and directories.
Display inode information:
ls –i
mkdir command:
rmdir command:
mv command:
diff command:
comm command:
wc command:
Disk utilities:
du (abbreviated from disk usage) is a standard Unix program used to estimate file
spaceusage—space used under a particular directory or files on a file system.
$du kt.txt pt.txt /* the first column displayed the file's disk usage */
8 kt.txt
4 pt.txt
Using -h option: As mentioned above, -h option is used to produce the output in
humanreadable format.
$du -h kt.txt pt.txt
8.0K
k
t.txt4.0K
p
t.txt
/*now the output is in human readable format i.e in
Kilobytes */Using -a option
$du -a kartik
8 kartik/kt.txt 4 kartik/thakral.png
4 kartik/pt.txt 4 kartik/thakral
4 kartik/pranjal.png 24 kartik
$df kt.txt
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/the2 1957124 1512 1955612 1% /snap/core
/* the df only showed the disk usage details of the file system that contains file kt.txt */
//using df without any filename //
$df
/* in this case df displayed the disk usage details of all mounted file systems */
Using -h : This is used to make df command display the output in human-readable format.
//using -h with df//
$df -h kt.txt
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/the2 1.9G 1.5M 1.9G 1% /snap/core
/*this output is easily understandable by the user and all cause of -h option */
Networking
commandsping
The ping command sends an echo request to a host available on the network. Using this
command, you can check if your remote host is responding well or not.
Syntax: $ping hostname or ip-address
The above command starts printing a response after every second. To come out of
thecommand, you can terminate it by pressing CNTRL + C keys.
$ping google.com
PING google.com (74.125.67.100) 56(84) bytes of data.
64 bytes from 74.125.67.100: icmp_seq=1 ttl=54 time=39.4 ms
ftp: ftp stands for File Transfer Protocol. This utility helps you upload and download your
filefrom one computer to another computer.
Syntax $ftp hostname or ip-address
$ftp amrood.com
Connected to amrood.com.
220 amrood.com FTP server (Ver 4.9 Thu Sep 2 20:35:07 CDT
2009)Name (amrood.com:amrood): amrood
331 Password required for
amrood.Password:
230 User amrood
logged in.ftp> dir
200 PORT command successful.
….
ftp> quit
221 Goodbye.
C:>telnet
amrood.com
Trying...
Connected to
amrood.com.Escape
character is '^]'. login:
amrood
amrood's Password:
***************************************************
***WELCOME TO AMROOD.COM *
***************************************************** $ logout
Connection
closed.C:>
Finger:
The finger command displays information about users on a given host. The host can be
eitherlocal or remote.
Check all the logged-in users on the local machine −
$ finger
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
Check all the logged-in users on the remote machine –
$ finger @avtar.com
Login Name Tty Idle Login Time
Office amrood pts/0 Jun 25 08:03
(62.61.164.115)
Get the information about a specific user available on the remote machine −
$ finger [email protected]
Ifconfig: Ifconfig is used to configure the network interfaces.
Filters
more COMMAND:
more command is used to display text in the terminal screen. It allows only
backwardmovement.
1. more -c index.txt
Clears the screen before printing the file .
2. more -3 index.txt
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND:
head command is used to display the first ten lines of a file, and also specifies how many
linesto display.
1. head index.php
tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays
last10 lines of a file.
1. tail index.php
It displays the last 10 lines of 'index.php'.
2. tail -2 index.php
It displays the last 2 lines of 'index.php'.
3. tail -n 5 index.php
It displays the last 5 lines of 'index.php'.
4. tail -c 5 index.php
It displays the last 5 characters of 'index.php'.
cut COMMAND:
cut command is used to cut out selected fields of each line of a file. The cut command
usesdelimiters to determine where to split fields.
cut -c1-3
text.txt
Output:
Thi
Cut the first three letters from the above line.
paste COMMAND:
paste command is used to paste the content from one file to another file. It is also used to
setcolumn format for each line.
paste test.txt>test1.txt
Paste the content from 'test.txt' file to 'test1.txt' file.
sort COMMAND:
sort command is used to sort the lines in a text file.
1. sort test.txt
Sorts the 'test.txt'file and prints result in the screen.
2. sort -r test.txt
Sorts the 'test.txt' file in reverse order and prints result in the screen.
uniq
Report or filter out repeated lines in a file.
uniq myfile1.txt > myfile2.txt - Removes duplicate lines in the first file1.txt and outputs
theresults to the second file.
Text processing utilities
echo: display a line of text or echo command prints the given input string to standard output.
Backup utilities
Linux backup and restore can be done using backup commands tar, cpio, dump and restore.
Backup Restore using tar command
tar: tape archive is used for single or multiple files backup and restore on/from a tape or file.
$tar cvf /dev/rmt/0 *
Options: c -> create ; v -> Verbose ; f->file or archive device ; * -> all files and directories .
$tar cvf /home/backup *
Create a tar called backup in home directory, from all file and directories s in the
currentdirectory.
Viewing a tar backup on a tape or file
$tar tvf /dev/rmt/0 ## view files backed up on a tape device.
$tar tvf /home/backup ## view files backed up inside the backup
Note: t option is used to see the table of content in a tar file.
Using cpio command to backup all the files in current directory to tape.
Aim:-Write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or directory and reports accordingly. Whenever the
argument is a file it reports no of lines present in it
ALGORITHM:
step 1: if arguments are less than 1 print Enter at least one input file name and goto
step 9Step 2: selects list a file from list of arguments provided in command line
Step 3: check for whether it is directory if yes print is directory and goto
step 9step 4: check for whether it is a regular file if yes goto step 5 else
goto step 8 Step 5: print given name is regular file
step 6: print No of lines in
filestep 7: goto step
step 8: print not a file or a
directorystep 9: stop
Expected Output:
[root@localhost sh]# sh 2a.sh
abc1.txtmrcet given name is file:
abc1.txt
CPU SCHEDULINGALGORITHMS
AIM: To write a c program to simulate the CPU scheduling algorithm First Come First
Serve(FCFS)
DESCRIPTION:
To calculate the average waiting time using the FCFS algorithm first the waiting time of the first
process is kept zero and the waiting time of the second process is the burst time of the first
process and the waiting time of the third process is the sum of the burst times of the first and the
second process and so on. After calculating all the waiting times the average waiting time is
calculated as the average of all the waiting times. FCFS mainly says first come first serve the
algorithm which camefirst will be served first.
ALGORITHM:
SOURCE CODE :
#include<stdio.h>
#include<conio
.h>main()
{
int bt[20], wt[20], tat[20],
i, n;float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d",&
n);
for(i=0;i<n;i+
+)
P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time --17.000000
Average Turnaround Time --
27.000000 OUTPUT:
AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first (Non- Preemption)
DESCRIPTION:
To calculate the average waiting time in the shortest job first algorithm the sorting of the process based
on their burst time in ascending order then calculate the waiting time of each process as the sum of the
bursting times of all the process previous or before to that process.
ALGORITHM:
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‗0‘ and its turnaround time as its burst time.
Step 6: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
A) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
#include<stdio.h>
#include<conio.h>
main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++) for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
OPERATING SYSTEMS LAB PAGE 33
bt[i]=bt[k];
bt[k]=temp
;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}
INPUT:
Enter the number of processes --4
Enter Burst Time for Process 0 --6
Enter Burst Time for Process 1 --8
Enter Burst Time for Process 2 --7
Enter Burst Time for Process 3 –3
Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
P0 6 3 9
P1 8 16 24
P2 7 9 16
P3 3 0 3
OUTPUT:
DESCRIPTION:
To aim is to calculate the average waiting time. There will be a time slice, each process should be
executed within that time-slice and if not it will go to the waiting state so first check whether the
burst time is less than the time-slice. If it is less than it assign the waiting time to the sum of the total
times. If it is greater than the burst-time then subtract the time slot from the actual burst time and
increment it by time-slot and the loop continues until all the processes are completed.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where No. of time slice for process (n) = burst
time process (n)/time slice
Step 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 timeof process(n-1 ) + the
time difference in getting the CPU fromprocess(n-1)
b) Turnaround 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
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 8: Stop the process
SOURCE CODE
#include<stdio.h>
main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
DESCRIPTION:
To calculate the average waiting time in the priority algorithm, sort the burst times according to
their priorities and then calculate the average waiting time of the processes. The waiting time
ofeach process is obtained by summing up the burst times of all the previous processes.
ALGORITHM:
SOURCE CODE :
#include<stdio.h>
#include<stdlib.h>
struct process
{
int process_id;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
};
int main()
{
int n, i;
OPERATING SYSTEMS LAB PAGE 37
struct process proc[10];
{
printf("\nEnter the process ID: ");
scanf("%d", &proc[i].process_id);
priority_scheduling(proc, n);
return 0;
}
find_waiting_time(proc, n, wt);
find_turnaround_time(proc, n, wt, tat);
temp = proc[i];
proc[i] = proc[pos];
proc[pos] = temp;
}
find_average_time(proc, n);
}
INPUT:
Enter the number of processes: 3
Enter the process ID: 1 Enter the burst time: 5 Enter the priority: 2
Enter the process ID: 2 Enter the burst time: 2 Enter the priority: 1
Enter the process ID: 3 Enter the burst time: 4 Enter the priority: 3
Process ID Burst Time Priority Waiting Time Turnaround Time 2 2 1 0 2 1 5 2 2 7 3 4 3 7 11
Average Waiting Time = 3.000000 Average Turnaround Time = 6.666667
AIM: Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)
DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to finish, and
thus neither ever does. When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of resources in the
system. When the user request a set of resources, the system must determine whether the allocation of
each resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.
Data structures 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
Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i] =False.
1. Find an i such that both
2. 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 process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request i and the
oldresource-allocation state is restored.
ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
OPERATING SYSTEMS LAB PAGE 40
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safestate.
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.
11. End.
SOURCE CODE :
#include<stdio.h>
int main()
{
/* array will store at most 5 process with 3 resoures if your process or
resources is greater than 5 and 3 then increase the size of array */
int p, c, count = 0, i, j, alc[5][3], max[5][3], need[5][3], safe[5], available[3], done[5], terminate = 0;
printf("Enter the number of process and resources");
scanf("%d %d", & p, & c);
// p is process and c is diffrent resources
printf("enter allocation of resource of all process %dx%d matrix", p, c);
for (i = 0; i < p; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d", & alc[i][j]);
}
}
printf("enter the max resource process required %dx%d matrix", p, c);
for (i = 0; i < p; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d", & max[i][j]);
}
}
printf("enter the available resource");
for (i = 0; i < c; i++)
scanf("%d", & available[i]);
/* once process execute variable done will stop them for again execution */
for (i = 0; i < p; i++)
{
done[i] = 0;
}
while (count < p)
{
for (i = 0; i < p; i++)
{
if (done[i] == 0)
{
for (j = 0; j < c; j++)
{
if (need[i][j] > available[j])
break;
}
//when need matrix is not greater then available matrix then if j==c will true
if (j == c)
{
safe[count] = i;
done[i] = 1;
/* now process get execute release the resources and add them in available resources */
for (j = 0; j < c; j++)
{
available[j] += alc[i][j];
}
count++;
terminate = 0;
} else {
terminate++;
}
}
}
if (terminate == (p - 1))
{
printf("safe sequence does not exist");
break;
}
}
if (terminate != (p - 1))
{
printf("\n available resource after completion\n");
for (i = 0; i < c; i++)
{
printf("%d\t", available[i]);
}
printf("\n safe sequence are\n");
for (i = 0; i < p; i++)
{
OPERATING SYSTEMS LAB PAGE 42
printf("p%d\t", safe[i]);
}
}
return 0;
}
OUTPUT:
Banker‘s Algorithm:
When a new process enters a system, it must declare the maximum number of instances of each resource
type it needed. This number may exceed the total number of resources in the system. When the user
request a set of resources, the system must determine whether the allocation of each resources will leave
the system in safe state. If it will the resources are allocation; otherwise the process must wait until
some other process release the resources.
DESCRIPTION
ALGORITHM:
SOURCE CODE :
// Banker's Algorithm
#include<stdio.h>
int main()
{
// P0 , P1 , P2 , P3 , P4 are the Process names here
int n , m , i , j , k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[ 5 ] [ 3 ] = { { 0 , 1 , 0 }, // P0 // Allocation Matrix
OPERATING SYSTEMS LAB PAGE 45
{ 2 , 0 , 0 } , // P1
{ 3 , 0 , 2 } , // P2
{ 2 , 1 , 1 } , // P3
{ 0 , 0 , 2 } } ; // P4
int max[ 5 ] [ 3 ] = { { 7 , 5 , 3 } , // P0 // MAX Matrix
{ 3 , 2 , 2 } , // P1
{ 9 , 0 , 2 } , // P2
{ 2 , 2 , 2 } , // P3
{ 4 , 3 , 3 } } ; // P4
int avail[3] = { 3 , 3 , 2 } ; // Available Resources
int f[n] , ans[n] , ind = 0 ;
for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j] ;
}
int y = 0;
for (k = 0; k < 5; k++){
for (i = 0; i < n; i++){
if (f[i] == 0){
int flag = 0;
for (j = 0; j < m; j++) {
if(need[i][j] > avail[j]){
flag = 1;
break;
}
}
if ( flag == 0 ) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y] ;
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i] == 0)
{
flag = 0;
printf(" The following system is not safe ");
break;
}
}
OPERATING SYSTEMS LAB PAGE 46
if (flag == 1)
{
Expected Output:
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2
........................................................
Process execute din 1.33 seconds
OUTPUT:
DESCRIPTION
The dining-philosophers problem is considered a classic synchronization problem because it is an
example of a large class of concurrency-control problems. It is a simple representation of the need to
allocate several resources among several processes in a deadlock-free and starvation-free manner.
Consider five philosophers who spend their lives thinking and eating. The philosophers share a circular
table surrounded by five chairs, each belonging to one philosopher. In the center of the table is a bowl of
rice, and the table is laid with five single chopsticks. When a philosopher thinks, she does not interact
with her colleagues. From time to time, a philosopher gets hungry and tries to pick up the two chopsticks
that are closest to her (the chopsticks that are between her and her left and right neighbors). A
philosopher may pick up only one chopstick at a time. Obviously, she cam1ot pick up a chopstick that is
already in the hand of a neighbor. When a hungry philosopher has both her chopsticks at the same time,
she eats without releasing her chopsticks. When she is finished eating, she puts down both of her
chopsticks and starts thinking again. The dining-philosophers problem may lead to a deadlock situation
and hence some rules have to be framed to avoid the occurrence of deadlock.
PROGRAM:
#include<stdio.h>
void one();
void two();
int tph, philname[20], status[20], howhung, hu[20], cho;
main()
{
int i;
printf("\n\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total no. of philosophers: ");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i]=(i+1);
status[i]=1;
}
printf("How many are hungry : ");
scanf("%d", &howhung);
if(howhung==tph)
{
printf("\n All are hungry..\nDead lock stage will occur");
printf("\nExiting\n");
}
else
{
for(i=0;i<howhung;i++)
{
printf("Enterphilosopher%dposition:",(i+1));
scanf("%d",&hu[i]);
status[hu[i]]=2;
}
do
{
OPERATING SYSTEMS LAB PAGE 48
printf("1.One can eat at a time\t2.Two can eat at a time\t3.Exit\nEnter your choice:");
scanf("%d", &cho);
switch(cho)
{
case 1:one();
break;
case 2:two();
break;
case 3:
exit(0);
default: printf("\nInvalid option..");
}
}while(1);
}
}
one()
{
int pos=0, x, i;
printf("\nAllow one philosopher to eat at any time\n");
for(i=0;i<howhung; i++, pos++)
{
printf("\nP %d is granted to eat", philname[hu[pos]]);
for(x=pos;x<howhung;x++)
printf("\nP %d is waiting", philname[hu[x]]);
}
}
two()
{
int i, j, s=0, t, r, x;
printf("\n Allow two philosophers to eat at same time\n");
for(i=0;i<howhung;i++)
{
for(j=i+1;j<howhung;j++)
{
if(abs(hu[i]-hu[j])>=1&& abs(hu[i]-hu[j])!=4)
{
printf("\n\ncombination %d \n", (s+1)); t=hu[i];
r=hu[j]; s++;
printf("\nP %d and P %d are granted to eat", philname[hu[i]], philname[hu[j]]);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}
}
}
INPUT:
P 3 is granted to eat
P 3 is waiting
P 5 is waiting
P 0 is waiting
P 5 is granted to eat
P 5 is waiting
P 0 is waiting
P 0 is granted to eat
P 0 is waiting1.One can eat at a time 2.Two can eat at a time 3.Exit
OUTPUT:
DESCRIPTION
Producer consumer problem is a synchronization problem. There is a fixed size buffer where the
producer produces items and that is consumed by a consumer process. One solution to the producer-
consumer problem uses shared memory. To allow producer and consumer processes to run
concurrently, there must be available a buffer of items that can be filled by the producer and emptied by
the consumer. This buffer will reside in a region of memory that is shared by the producer and
consumer processes. The producer and consumer must be synchronized, so that the consumer does not
try to consume an item that has not yet been produced.
PROGRAM
#include<stdio.h>
int main()
{
int buffer[10], bufsize, in, out, produce, consume, choice = 0;
in = 0;
out = 0;
bufsize = 10;
while (choice != 3)
{
printf("\n1. Produce \t\n2. Consume \t\n3. Exit");
printf("\n Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
if ((in + 1) % bufsize == out)
printf("\nBuffer is Full");
else
{
printf("\nEnter the value: ");
scanf("%d", &produce);
buffer[in] = produce;
in = (in + 1) % bufsize;
}
break;
case 2:
if (in == out)
printf("\nBuffer is Empty");
else
{
consume = buffer[out];
printf("\nThe consumed value is %d", consume);
out = (out + 1) % bufsize;
OPERATING SYSTEMS LAB PAGE 51
}
break;
}
return 0;
}
Expected Output:
OUTPUT:
A. Aim:- Write a C program that illustrate communication between two process using
namedpipes or FIFO
Algorithm:
Create two processes, one is fifoserver_twoway and another one is fifoclient_twoway.
Algorithm for fifoserver_twoway :
step 1:Start
step 2: Creates a named pipe (using library function mkfifo())
with name ―fifo_twoway‖ in /tmp directory, if not created.
step 3: Opens the named pipe for read and write purposes.
step 4: Here, created FIFO with permissions of read and write for Owner. Read for Group and no
permissions for Others.
step 5: Waits infinitely for a message from the client.
step 6: If the message received from the client is not ―end‖, prints the message and
reverses the string. The reversed string is sent back to the client. If the message is ―end‖,
closes the fifo and ends the process.
step 7:stop.
Program:
/* Filename: fifoserver_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int fd;
char readbuf[80];
char end[10]; int
to_end;
mkfifo(FIFO_FILE, S_IFIFO|0640);
strcpy(end, "end");
fd = open(FIFO_FILE, O_RDWR);
while(1) {
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOSERVER: Received string: \"%s\" and length is %d\n", readbuf,
(int)strlen(readbuf));
to_end = strcmp(readbuf, end);
if (to_end == 0) {
close(fd); break;
}
reverse_string(readbuf);
printf("FIFOSERVER: Sending Reversed String: \"%s\" and length is %d\n", readbuf, (int)
strlen(readbuf));
write(fd, readbuf, strlen(readbuf));
/*
sleep - This is to make sure other process reads this, otherwise this
process would retrieve the message
*/ sleep(2);
}
return 0;
}
Expected Output:
FIFOSERVER: Received string: "LINUX IPCs" and length is 10
FIFOSERVER: Sending Reversed String: "sCPI XUNIL" and length is 10
FIFOSERVER: Received string: "Inter Process Communication" and length is 27
FIFOSERVER: Sending Reversed String: "noitacinummoC ssecorP retnI" and length is 27
FIFOSERVER: Received string: "end" and length is 3
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define FIFO_FILE "/tmp/fifo_twoway"
int main() {
int fd;
int end_process;
int stringlen;
int read_bytes;
char readbuf[80];
char end_str[5];
printf("FIFO_CLIENT: Send messages, infinitely, to end enter \"end\"\n");
fd = open(FIFO_FILE, O_CREAT|O_RDWR);
strcpy(end_str, "end");
while (1) {
printf("Enter string: ");
fgets(readbuf, sizeof(readbuf), stdin);
stringlen = strlen(readbuf);
readbuf[stringlen - 1] = '\0';
end_process = strcmp(readbuf, end_str);
//printf("end_process is %d\n", end_process);
if (end_process != 0) {
write(fd, readbuf, strlen(readbuf));
printf("FIFOCLIENT: Sent string: \"%s\" and string length is %d\n", readbuf,(int)strlen(readbuf));
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOCLIENT: Received string: \"%s\" and length is %d\n", readbuf,(int)strlen(readbuf));
} else {
write(fd, readbuf, strlen(readbuf));
printf("FIFOCLIENT: Sent string: \"%s\" and string length is %d\n", readbuf,(int)strlen(readbuf));
close(fd);
break;
}
}
return 0;
}
Expected Output:
FIFO_CLIENT: Send messages, infinitely, to end enter "end" Enter string: LINUX IPCs
FIFOCLIENT: Sent string: "LINUX IPCs" and string length is 10
FIFOCLIENT: Received string: "sCPI XUNIL" and length is 10 Enter string: Inter Process Communication
FIFOCLIENT: Sent string: "Inter Process Communication" and string length is 27
FIFOCLIENT: Received string: "noitacinummoC ssecorP retnI" and length is 27 Enter string: end
FIFOCLIENT: Sent string: "end" and string length is 3
Algorithm:
Step 1:Start
Step 2:Declare a message queue structuretypedef struct msgbuf { long mtype;
char mtext[MSGSZ];
} message_buf;
Mtype =0Retrieve the next message on the queue, regardless of its mtype.
PositiveGet the next message with an mtype equal to the specifiedmsgtyp.
Negative Retrieve the first message on the queue whose mtype fieldisless than or equal to the absolute
value of the msgtyp argument.Usually mtype is set to1 mtext is the data this will be added to the queue.
Step 3:Get the message queue id for the "name" 1234, which was created by the serverkey = 1234
int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, intmsgflg);
Message flag:The msgflg argument is a bit mask constructed by ORing together zero ormore
of the following flags: IPC_NOWAIT or MSG_EXCEPT or MSG_NOERROR
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE
128void die(char *s)
{
perror(s);
exit(1);
}
OUTPUT:
Aim:-Write a C program that illustrates two processes communicating using Shared memory
Algorithm:-
step1.Start
step 2.Include header files required for the
program are
#include <sys/types.h>
#include<sys/ipc.>
#include<sys/shm.>
#include <unistd.h>
#include <string.h>
#include <errno.h>
step 3.Declare the variable which are required aspid_t pidint *shared /* pointer to the shm */int shmid
step 4. Use shmget function to create shared
memory#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg)
The shmget() function shall return the shared memory identifier associated with key The
argumentkey is equal to IPC_PRIVATE. so that the operating system selects the next
Available key for a newly created shared block of memory. Size
represents size of shared memory block Shmflg shared memory permissions which are
represented by octalinteger shmid = shmget (IPC_PRIVATE, sizeof(int), IPC_CREAT |
0666);
print the shared memory id
step 5.if fork()==0
Then begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared) *shared=2print
*shared sleep(2)
print *shared
end
step 6.else
begin
shared = shmat(shmid, (void *) 0, 0)print the shared variable(shared) print *shared sleep(1)
*shared=30
step 7.stop
Sha.c
#include<sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
DESCRIPTION:
Page replacement algorithms are an important part of virtual memory management and it helps the OS to
decide which memory page can be moved out making space for the currently needed page. However, the
ultimate objective of all page replacement algorithms is to reduce the number of page faults.
FIFO-This is the simplest page replacement algorithm. In this algorithm, the operating system keeps
track of all pages in the memory in a queue, the oldest page is in the front of the queue. When a page
needs to bereplaced page in the front of the queue is selected for removal.
LRU-In this algorithm page will be replaced which is least recently used
OPTIMAL- In this algorithm, pages are replaced which would not be used for the longest duration of
time in the future. This algorithm will give us less page fault when compared to other page replacement
algorithms.
ALGORITHM:
1. Start the process
6. Replace the page with circular queue, while re-placing check page availability in the frame Place
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int flag1=0,flag2=0,pf=0,frsize=3,top=0;
OUTPUT:
SOURCE CODE :
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;
for(i=0;i<3;i++)
fr[i]=-1;
for(j=0;j<12;j++)
flag1=0,
flag2=0;
if(fr[i]==p[j])
flag1=1;
flag2=1;
break;
if(flag1==0)
for(i=0;i<3;i++)
if(fr[i]==-1)
fr[i]=p[j];
flag2=1;
break;
if(flag2==0)
for(i=0;i<3;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
for(i=0;i<3;i++)
if(fr[i]==p[k])
fs[i]=1;
}}
for(i=0;i<3;i++)
if(fs[i]==0)
index=i;
fr[index]=p[j];
pf++;
display();
void display()
int i;
printf("\n");
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
Expected Output:
2 -1 -1
2 3 -1
2 3 -1
2 3 1
2 5 1
2 5 1
2 5 4
3 5 4
3 5 2
3 5 2
3 5 2
no of page faults :7
OUTPUT:
ALGORTHIM:
1. Start Program
6. If No Frames Is Free Repalce The Page With The Page That Is Leastly Used
8. Stop process.
SOURCE CODE:
Expected Output:
Enter length of the reference string: 12
Enter the reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Enter no of frames: 3
1 -1 -1
1 2 -1
OUTPUT:
Aim: Write a C program that takes one or more file/directory names as command
lineinput and reports following information
A)File Type B)Number Of Links
C) Time of last Access D) Read, write and execute permissions
Algorithm:
Step 1:start
Step 5:Check whether the given file is Directory file by using S_ISDIR(a.st_mode) if it is a directory
file
Step 9:stop
Program:
#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
int main(int argc,char *argv[])
{
int i,j; struct
stat a;
for (i=1;i<argc;i++)
{
printf("%s : ",argv[i]); stat(argv[i],&a);
if(S_ISDIR(a.st_mode))
{
printf("is a Directory file\n");
}
else
{
printf("is Regular file\n");
}
printf("Inode Number:%d\n",a.st_ino);
printf("UID:%o\n",a.st_uid);
printf("GID:%o\n",a.st_gid);
OUTPUT:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main()
int RQ[100],i,n,TotalHeadMoment=0,initial;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
scanf("%d",&initial);
for(i=0;i<n;i++)
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
return 0;
INPUT
Expected Output:
OUTPUT:
#include<stdio.h>
main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
clrscr();
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;
t[1]=h;
printf("enter the tracks");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<n+2;i++)
{
for(j=0;j<(n+2)-i-1;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}}}
for(i=0;i<n+2;i++)
if(t[i]==h)
j=i;k=i;
p=0;
while(t[j]!=0)
{
atr[p]=t[j];
j--;
p++;
}
atr[p]=t[j];
for(p=k+1;p<n+2;p++,k++)
atr[p]=t[k+1];
for(j=0;j<n+1;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
INPUT
Expected Output:
OUTPUT:
#include<stdio.h>
main()
scanf("%d",&n);
scanf("%d",&h);
t[0]=0;
t[1]=h;
scanf("%d",&tot);
t[2]=tot-1;
for(i=3;i<=n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<=n+2;i++)
for(j=0;j<=(n+2)-i-1;j++)
if(t[j]>t[j+1])
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
for(i=0;i<=n+2;i++)
j=i;
break;
p=0;
while(t[j]!=tot-1)
atr[p]=t[j];
j++;
p++;
atr[p]=t[j];
p++;
i=0;
atr[p]=t[i];
i++;
p++;
for(j=0;j<n+2;j++)
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
d[j]=atr[j+1]-atr[j];
sum+=d[j];
printf("avg is %f",(float)sum/n);
INPUT:
Expected Output:
OUTPUT: