OS - Lab
OS - Lab
OS - Lab
LABORATORY MANUAL
R20A0584
Affiliated to JNTUH, Hyderabad, Approved by AICTE ‐ Accredited by NBA Tier 1 & NAAC – ‘A’ Grade ‐ ISO 9001:2015Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING – AI & ML
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 to
improve the teaching pedagogy by using innovative techniques.
To strengthen the knowledge base of the faculty and students with motivation
towards possession of effective academic skills and relevant research
experience
To promote the necessary moral and ethical values among the engineers, for
the betterment of the society
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
1. Students are advised to come to the laboratory atleast 5 minutes before (to the starting
time), those who come after 5minutes 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 upto the last session experiments and other utensils (if
any)needed in the lab.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Executeyourtaskinthelaboratory,andrecordtheresults/outputinthelabobservationnotebook,a
nd 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. Computerlabsareestablishedwithsophisticatedandhighendbrandedsystems, 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 any
body 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
kept properly.
WEEK-1 Practice File handling utilities, Process utilities, Disk utilities, Networking
commands, Filters, Test processing utilities and Backup utilities.
WEEK-2 Simulate the following CPU scheduling algorithms.
a)FCFS b) SJF c) Round Robin d) Priority.
WEEK-3 Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers
Algorithm for Dead Lock Prevention
WEEK-4 Write a C program to simulate the concept of Dining-philosophers
problem.
Write a C program to simulate producer-consumer problem using
WEEK-5 Semaphores
a)Write a C program to implement kill(), raise() and sleep(),functions.
WEEK-6 b)Write a C program to implement alarm(), pause() and abort() functions
a) Write a program that illustrates communication between two process
WEEK-7 using named pipes or FIFO.
b) Write a C program that illustrates two processes communicating
using Shared memory
bg Send to background
cd Change Directory
dc Desk Calculator
op Operator access
ps Process status
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 file
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 into
thefile, 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 can
print 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 the
same 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 the
directory (thedirectory is not overwritten).
Ex:
ls COMMAND:
ls command lists the files and directories under current working directory. Display root
directorycontents:
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
ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for desired files.
Inode will be different for source and destination.
ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt' and
'file2.txt'will be different.
mkdir command:
rmdir command:
mv command:
diff command:
comm command:
wc command:
Process utilities:
ps Command:
ps command is used to report the process status. ps is the short name for Process Status.
1. ps: List the current running processes.
Output:
PID TTY TIME CMD
2540 pts/1 00:00:00 bash
2. ps –f : Displays full information about currently running processes.
Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
3. kill COMMAND: kill command is used to kill the background process.
Step by Step process:
• Open a process music player or any file.
xmms
press ctrl+z to stop the process.
• To know group id or job id of the background task.
jobs -l
It will list the background jobs with its job id as,
• xmms 3956
• kmail 3467
To kill a job or process.
• kill 3956
kill command kills or terminates the background process xmms.
Disk utilities:
du (abbreviated from disk usage) is a standard Unix program used to estimate file space
usage—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 human
readable format.
$du -h kt.txt pt.txt
8.0K kt.txt
4.0K pt.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
/*so with -a option used all the files (under directory kartik) disk usage info is displayed along
with the thakral sub-directory */
$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 commands
ping
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 the
command, 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 file
from 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.
telnet:
Telnet is a utility that allows a computer user at one site to make a connection, login and then
conduct work on a computer at another site. Once you login using Telnet, you can perform all
the activities on your remotely connected machine.
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 either
local 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 backward
movement.
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 lines
to display.
1. head index.php
This command prints the first 10 lines of 'index.php'.
2. head -5 index.php
The head command displays the first 5 lines of 'index.php'.
3. head -c 5 index.php
The above command displays the first 5 characters of 'index.php'.
tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays last
10 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 uses
delimiters 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 set
column 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 the
results to the second file.
Text processing utilities
echo: display a line of text or echo command prints the given input string to standard output.
eg. echo I love India
echo $HOME
wc: print the number of newlines, words, and bytes in files
eg. wc file1.txt
nl: which lets you number lines in files.
eg. $ nl file1
1 hi
join- Join command is used for merging the lines of different sorted files based on the
presence of common field into a single line. The second line will be appended at the end of
the first line and cursor is placed at the end of line after joining.
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 current
directory.
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.
Extracting tar backup from the tape
$tar xvf /home/backup ## extract / restore files in to current directory.
Note : x option is used to extract the files from tar file. Restoration will go to present directory
or original backup path depending on relative or absolute path names used for backup.
Backup restore using cpio command
Using cpio command to backup all the files in current directory to tape.
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 came
first will be served first.
ALGORITHM:
SOURCE CODE :
#include<stdio.h>
int main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
printf("\n Enter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
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("\t PROCESS \t BURST 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", i, bt[i], wt[i], tat[i]);
printf("\n Average Waiting Time --%f", wtavg/n);
printf("\n Average Turnaround Time -- %f", tatavg/n);
}
INPUT:
Enter the number of processes – 3
Enter Burst Time for Process 0 -- 24
Enter Burst Time for Process 1 -- 3
P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time --17.000000
Average Turnaround Time -- 27.000000
OUTPUT:
B. SHORTEST JOB FIRST:
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>
int 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];
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);
}
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:
C.ROUND ROBIN:
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>
int 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];
for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i]; awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
Expected Output:
The Average Turnaround time is -- 15.000000
The Average Waiting time is --5.000000
D.PRIORITY:
AIM: To write a c program to simulate the CPU scheduling priority algorithm.
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 of
each process is obtained by summing up the burst times of all the previous processes.
ALGORITHM:
SOURCE CODE :
#include<stdio.h>
int 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];
for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
Expected Output:
The Average Turnaround time is -- 15.000000
The Average Waiting time is --5.000000
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.
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 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 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>
void main()
{
int work[5],avl[5],alloc[10][10],l;
int need[10][10],n,m,I,j,avail[10],max[10][10],k,count,i,fcount=0,pr[10];
char finish[10]={'f','f','f','f','f','f','f','f','f','f'};
printf("\n enter the no of process");
scanf("%d",&n);
printf("\n enter the no of resources");
scanf("%d",&m);
printf("\n enter the total no of resources");
for(i=1;i<=m;i++)
scanf("%d",&avail[i]);
printf("\n enter the max resources req by each pr alloc matrix");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&max[i][j]);
printf("\n process allocation matrix");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&alloc[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
need[i][j]=max[i][j]-alloc[i][j];
for(i=1;i<=n;i++)
{
k=0;
for(j=1;j<=m;j++)
{
k=k+alloc[i][j];
}
avl[i]=avl[i]-k;
work[i]=avl[i];
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
{
count=0;
for(j=1;j<=m;j++)
{
if((finish[i]=='f')&&(need[i][j]<=work[i]))
count++;
}
if(count==m)
{
for(l=1;l<=m;l++)
work[l]=work[l]+alloc[i][l];
finish[i]='t';
pr[k]=i;
break;
}
}
for(i=1;i<=n;i++)
if(finish[i]=='t')
fcount++;
if(fcount==n)
{
}
else
Expected Output:
Enter the no of process 5
Enter the no of resources 3
Enter the total no of resources10 5 7
Enter the max resource req. by each pr alloc matrix
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
Process allocation matrix
0 1 0
2 0 0
3 0 2
2 1 1
0 2 2
The system is in safe state1
1
3
4
5
2
OUTPUT:
DEAD LOCKPREVENTION
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 :
#include<stdio.h>
void main()
{
char job[10][10];
int time[10],avail,tem[10],temp[10];
int safe[10];
int ind=1,i,j,q,n,t;
printf("Enter no of jobs: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name and time: ");
scanf("%s%d",&job[i],&time[i]);
}
printf("Enter the available resources:");
scanf("%d",&avail);
for(i=0;i<n;i++)
{
temp[i]=time[i];
tem[i]=i;
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(temp[i]>temp[j])
{
t=temp[i];
temp[i]=temp[j];
temp[j]=t;
t=tem[i];
tem[i]=tem[j];
tem[j]=t;
}
}
for(i=0;i<n;i++)
{
q=tem[i];
if(time[q]<=avail)
{
safe[ind]=tem[i];
avail=avail-tem[q];
printf("%s",job[safe[ind]]);
ind++;
}
else
{
printf("No safe sequence\n");
}
}
printf("Safe sequence is:");
for(i=1;i<ind; i++)
printf(" %s %d\n",job[safe[i]],
time[safe[i]]);
Expected Output:
Enter no of jobs: 4
Enter name and time: A 1
Enter name and time: B 4
Enter name and time: C 2
Enter name and time: D 3
Enter the available resources:20
Safe sequence is: A 1
C2
D3
B4
OUTPUT:
WEEK : 4
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>
#include<stdlib.h>
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
{
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:
Expected Output:
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
combination 1
P 0 is waiting
combination 2
P 5 is waiting
combination 3
OUTPUT:
WEEK : 5
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 2.Consume\t 3.Exit");
printf("\nEnter 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;
}break;
}
}
}
Expected Output:
OUTPUT:
WEEK : 6
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
// function declarationvoid
sighup();
if (pid == 0)
{ /* child */ signal(SIGHUP, sighup);
signal(SIGINT, sigint);
signal(SIGQUIT, sigquit);
for (;;)
; /* loop for ever */
}
else /* parent */
{ /* pid hold id of child */
printf("\nPARENT: sending SIGHUP\n\n");
kill(pid, SIGHUP);
sleep(3); /* pause for 3 secs */
printf("\nPARENT: sending SIGINT\n\n");
kill(pid, SIGINT);
sleep(3); /* pause for 3 secs */
printf("\nPARENT: sending SIGQUIT\n\n");
kill(pid, SIGQUIT);
sleep(3);
}
}
// sighup() function definition
void sighup()
{
signal(SIGHUP, sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP\n");
}
OUTPUT:
raise( ):
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void signal_handler(int signal)
{
/* Display a message indicating we have received a signal */
if (signal == SIGUSR1) printf("Received a SIGUSR1 signal\n");
return 0;
}
Expected Output:
OUTPUT:
B. Write a C program to implement alarm(), pause() and abort() functions.
#define _POSIX_SOURCE
#include <unistd.h>
#include
<signal.h>
#include
<stdio.h>
#include
<time.h>
void catcher(int signum) {puts("inside catcher. ");
}
void
timestamp()
{time_t t;
time(&t);
printf("the time is %s", ctime(&t));
}
main() {
struct sigaction sigact;
sigemptyset(&sigact.sa_mask
);sigact.sa_flags = 0;
sigact.sa_handler = catcher;
sigaction(SIGALRM, &sigact, NULL);
alarm(10);
printf("before
pause... ");
timestamp();
pause();
printf("after
pause... ");
timestamp();
}
Expected Output:
before pause... the time is Fri Jun 16
09:42:29 2001inside catcher...
OUTPUT:
abort():
OUTPUT:
WEEK :7
A. Aim:- Write a C program that illustrate communication between two process usingnamed
pipes 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;
int read_bytes;
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
/* Filename: fifoclient_twoway.c */
#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
OUTPUT:
B.Aim:-Write a C program that illustrates two processes communicating using Shared
memoryAlgorithm:-
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>
#include <errno.h>
int main(void)
{
pid_t pid;
int *shared; /* pointer to the shm */ int shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
printf("Shared MemoryID=%u",shmid);
if (fork() == 0) { /* Child */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0,
0);printf("Child pointer %u\n", shared);
*shared=1;
printf("Child value=%d\n", *shared);
sleep(2); printf("Child value=%d\n", *shared);
}
else { /* Parent */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0,
0);printf("Parent pointer %u\n", shared); printf("Parent value=%d\n", *shared); sleep(1);
*shared=42;
printf("Parent value=%d\n", *shared);
sleep(5);shmctl(shmid, IPC_RMID, 0);
}
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>
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;
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0;
flag2=0;
for(i=0;i<12;i++)
{
if(fr[i]==page[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}
OUTPUT:
B.LEAST RECENTLY USED
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;
for(i=0;i<3;i++)
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
2 5 4
3 5 4
3 5 2
3 5 2
3 5 2
no of page faults :7
OUTPUT:
C. OPTIMAL
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:
OUTPUT:
WEEK : 9
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);
printf("No of Links:%d\n",a.st_nlink);
printf("Last Access time:%s",asctime(localtime(&a.st_atime)));
OUTPUT:
WEEK : 10
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
-v Non-rinting characters (with the exception of tabs, new-lines & form-feeds) are printed visibly.
Operations With cat Command:
Step 4: read the date from specified file and write it to destination file
Step 5 : stop
Program :
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
{
int fd,n;
char buff[512];
if(argc!=2)
printf("ENTER CORRECT ARGUMENTS :");
if((fd=open(argv[1],4))<0)
{
printf("ERROR");
return 0;
}
while(n=read(fd,buff,sizeof(buff))>0)
write(1,buff,n);
}
OUTPUT:
II. AIM:-Write a c program to implement ls command using system calls
Algorithm:
Step 1: Start.
Step 2: open directory using opendir( ) system call.
Step 3: read the directory using readdir( ) system call.
Step 4: print dp.name and dp.inode.
Step 5: repeat above step until end of directory.
Step 6: Stop.
OUTPUT:
III. Aim :write a c program that simulates Scanning directories (using system calls)
Description:
Scanning directories is used to opendir(), readdir(), rewinddir(), closedir(), etc.)
Week:11
Aim: Write a C program to create child process and allow parent process to display “parent” andthe
child to display “child” on the screen
Algorithm:
Step 1: start
Step2: call the fork() function to create a childprocess fork function returns 2 values
step 3: which returns 0 to child process
step 4:which returns process id to the parent process
step 5:stop
else
{
pid2=getpid();
printf("\n the child process ID is %d\n", pid2);
}
}
Expected Output:
the child process ID is 4485
the parent process ID is 4484
OUTPUT:
WEEK : 12
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:
B. SCAN DISK SCHEDULING ALGORITHM
#include<stdio.h>
int 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 traversed ");
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
d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n);
}
INPUT
Expected Output:
OUTPUT:
C. C-SCAN DISK SCHEDULING ALGORITHM
#include<stdio.h>
int 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++)
{
if(t[i]==h)
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("total header movements%d\n",sum);
printf("avg is %f",(float)sum/n);
INPUT:
Expected Output:
OUTPUT: