0% found this document useful (0 votes)
2 views70 pages

List of Expts - OS

The document outlines basic Linux commands, shell programming examples, Unix system calls, and CPU scheduling algorithms. It includes commands for file management, process control, and user interaction, as well as sample programs demonstrating shell scripting and system calls. Additionally, it describes the implementation of First Come First Serve (FCFS) and Shortest Job First (SJF) scheduling algorithms in C programming.

Uploaded by

wasimrajaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views70 pages

List of Expts - OS

The document outlines basic Linux commands, shell programming examples, Unix system calls, and CPU scheduling algorithms. It includes commands for file management, process control, and user interaction, as well as sample programs demonstrating shell scripting and system calls. Additionally, it describes the implementation of First Come First Serve (FCFS) and Shortest Job First (SJF) scheduling algorithms in C programming.

Uploaded by

wasimrajaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Experiment No : 1 BASIC COMMANDS IN LINUX

Date :
Aim: To study the basic commands in Linux.

Commands:

1. Task: To display the files and folders present in the login.


Command: `ls`
Syntax: `ls`
Explanation: This command displays the files and folders in the current directory.

2. Task: To display the online manual.


Command: man
Syntax: man <command>
Explanation: This command displays the manual for the specified command.

3. Task: To view a file.


Command: cat
Syntax: cat <filename>
Explanation: This command displays the contents of the specified file.

4.Task: To create a file.


Command: vi
Syntax: vi <filename>
Explanation: This command opens a text editor to create or modify a file.

5. Task: To create a directory.


Command: mkdir
Syntax: mkdir <dirname>`
Explanation: This command creates a new directory with the specified name.

6. Task: To change the directory.


Command: `cd`
mSyntax: `cd <directory_name>`
Explanation: This command switches to the specified directory.

7. Task: To come out of a subdirectory.


Command: `cd ..`
Syntax: `cd ..`
Explanation: This command moves up to the parent directory.

8. Task: To display the current working directory.


Command: `pwd`
Syntax: `pwd`
Explanation: This command displays the current working directory.
9. Task: To delete a directory.
Command: `rmdir`
Syntax: `rmdir <directory_name>`
Explanation: This command deletes the specified directory.

10. Task: To copy a file.


Command: `cp`
Syntax: `cp <source_file> <destination_file>`
Explanation: This command copies the source file to the specified destination.

11. Task: To rename or move a file.


Command: `mv`
Syntax: `mv <source_file> <destination_file>`
Explanation: This command moves or renames the source file to the destination.

12. Task: To delete a file.


Command: `rm`
Syntax: `rm <filename>`
Explanation: This command deletes the specified file from the directory.

13. Task: To display the calendar of the current month.


Command: `cal`
Syntax: `cal`
Explanation: This command displays the calendar of the current month.

14. Task: To display a user-defined message.


Command: `echo`
Syntax: `echo "<message>"`
Explanation: This command displays the message after the `echo` command on the
screen.

15. Task: To display the details of all users.


Command: `who`
Syntax: `who`
Explanation: This command lists all users who are currently logged into the system.

16. Task: To display the current user detail.


Command: `whoami`
Syntax: `whoami`
Explanation: This command displays the username of the current user.

17.Task: To retrieve a part of a file.


Command: `head`
Syntax: `head -n <number_of_lines> <filename>`
Explanation: This command displays the specified number of lines from the top of the file.
18. Task: To retrieve a part of a file.
Command: `tail`
Syntax: `tail -n <number_of_lines> <filename>`
Explanation: This command displays the specified number of lines from the bottom of the
file.

19. Task: To sort the contents of a file.


Command: `sort`
Syntax: `sort <filename>`
Explanation: This command sorts the contents of the file in ascending order.

20. Task: To display the number of lines, words, and characters in a file.
Command: `wc`
Syntax: `wc <filename>`
Explanation: This command displays the number of lines, words, and characters in the
file.

21. Task: To compress a given file or directory.


Command: `gzip`
Syntax: `gzip <filename>`
Explanation: This command compresses the specified file or directory.

22. Task: To uncompress a file or directory.


Command: `gunzip`
Syntax: `gunzip <filename>`
Explanation: This command uncompresses the specified file or directory.

23. Task: To compare the contents of two files.


Command: `cmp`
Syntax: `cmp <file1> <file2>`
Explanation: This command compares two files and displays the differences.

24. Task: To find the difference between two files.


Command: `diff`
Syntax: `diff <file1> <file2>`
Explanation: This command compares two files and displays the differences.

25. Task: To match a given pattern in a file.


Command: `grep`
Syntax: `grep "<pattern>" <filename>`
Explanation: This command searches for the specified pattern in the file and displays the
matching lines.
26. Task: To change the permissions of a file.
Command: `chmod`
Syntax: `chmod <permissions> <filename>`
Explanation: This command changes the file permissions for the user, group, and others.

RESULT:

Thus the above Linux commands was verified and executed Successfully.
Experiment No : 2 Implementation of Shell Programming
Date :

1)Display the Statement using Echo Command

Aim: To display the given Statement using echo command.

Program:

Echo “SKCET COMPUTER SCIENCE AND ENGINEERING”;

Output:

Result:
The above program is executed Successfully.

2)To find the number is odd or even using shell programming

Aim:

To Find that given number is odd or even.

Program:

echo “Enter the number”


read n
r=’expr $n % 2’
if($r -eq 0)
then
echo “$n is an Even number”
else
echo “$n is an Even number”
fi
Output:

Result:
The above program is executed Successfully.

3)The given number is Armstrong or not.

Aim:

To find that the given number is Armstrong or not.

Program:

echo "Enter a number: "


read c
x=$c
sum=0
r=0
n=0
while [ $x -gt 0 ]
do
r=`expr $x % 10`
n=`expr $r \* $r \* $r`
sum=`expr $sum + $n`
x=`expr $x / 10`
done
if [ $sum -eq $c ]
then
echo "It is an Armstrong Number."
else
echo "It is not an Armstrong Number."
Fi
Output:

Result:

The above program is executed Successfully.

4)To find the factorial of a given Number.

Aim:

To find the Factorial for a given number

Program:

echo "Enter a number"


read n
factorial=1
for (( i=1; i<=n; i++ ))
do
factorial=$((factorial * i))
done
echo "Factorial of $n is $factorial"

Output:
Result:
The above program is executed Successfully.

5)To display the week days from 1 to 7. If it exists then print invalid.

Aim:

To display the week days from 1 to 7 if exists then print invalid.

Program:

echo "Enter a number (1-7)"


read day
case $day in
1) echo "Sunday" ;;
2) echo "Monday" ;;
3) echo "Tuesday" ;;
4) echo "Wednesday" ;;
5) echo "Thursday" ;;
6) echo "Friday" ;;
7) echo "Saturday" ;;
*) echo "Invalid Day." ;;
esac

Output:

Result:

The above program is executed Successfully.


Experiment No: 3 Implementation of Unix System Calls.

Date :

DESCRIPTION:

When a computer is turned on, the program that gets executed first is called the
“operating system”. It controls pretty much all activity in the computer. This includes
who logs in, how disks are used, how memory is used, how the CPU is used, and how
you talk with other computers. The operating system we use is called "Unix".
The way that programs talk to the operating system is via ``system calls.'' A system call
looks like a procedure call but it's different -- it is a request to the operating system to
perform some activity.

1.fork( )

Fork system call used for creating a new process, which is called child process, which
runs concurrently with a process (which process called system call fork) and this process
is called parent process. It takes no parameters and returns an integer value.
Negative Value: creation of a child process was unsuccessful.
Zero: Returned to the newly created child process.
Positive value: Returned to parent or caller. The value contains process ID of newly
created child process
Syntax: fork( )

2.wait( )

A call to wait() blocks the calling process until one of its child processes exits or a signal
is received. After the child process terminates, the parent continues its execution after the
wait system call instruction.
Syntax: wait( NULL)

3.exit( )

A process terminates when it finishes executing its final statement and asks the operating
system to delete it by using the exit system call. At that point, the process may return data
(output) to its parent process (via the wait system call).
Syntax: exit(0)
4.getpid( )
It returns the process ID of the current process.
Syntax : getpid()

5.getppid( )
It returns the process ID of the parent of the current process.
Syntax : getppid()

6.perror( )
Indicate the process error.
Syntax : perror()

7.opendir( )
Open a directory. Syntax : opendir()

8.readdir( )
Read a directory. Syntax : readdir()

9.closedir()
Close a directory. Syntax : closedir()

10.open()
It is used to open a file for reading, writing or both Syntax : open( const char* path, int
flags[, int mode ] ) Modes O_RDONLY: read only, O_WRONLY: write only,
O_RDWR: read and write, O_CREAT: create file if it doesn‟t exist, O_EXCL: prevent
creation if it already exists.

Example:
int fd = open("foo.txt", O_RDONLY | O_CREAT); printf("fd = %d/n", fd);

11.close ()

Tell the operating system you are done with a file descriptor and Close the file which is
pointed by fd.
Syntax: close(fd);

12.read ()
The file indicated by the file descriptor fd, the read() function reads cnt bytes of input
into the memory area indicated by buf. To read data from is said to be buf. A successful
read() updates the access time for the file.

fd: file descriptor


buf: buffer to read data from
cnt: length of buffer
Syntax: read(int fd, void* buf,size_t cnt); Example:
int fd = open("foo.txt", O_RDONLY); read(fd, &c, 1);

13.Write()
Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be
greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write() simply
returns 0 without attempting any other action.
Syntax : write(int fd, void* buf, size_t cnt); Example:
int fd = open("foo.txt", O_WRONLY | O_CREAT ); write(fd, "hello world", strlen("hello
world"));

PROGRAMS

1)Implementation of process management using the following system calls of the UNIX
operating system: fork, wait, exec, getpid, getppid and exit.

AIM:

To implement the process management system call commands of fork, wait, exec,
getpid, getppid and exit.

ALGORITHM:

STEP1: Declare the variable.


STEP2: Assign value to the variable by calling the function fork().
STEP3: Check if the variable is lesser than 0 and print Error.
STEP4: Else check if the variable is equal to 0 and print getpid() and getppid() and exit.
STEP5: Else call wait() function with NULL parameter, then print getpid().
Coding:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
int pid;
pid = fork();
if (pid < 0) {
printf("Error");
} else if (pid == 0) {
printf("Child Process\n");
printf("Child ID: %d\n", getpid());
printf("Parent ID: %d\n", getppid());
exit(0);
} else {
printf("Parent Process\n");
wait(NULL);
printf("Parent ID: %d\n", getpid());
}
return 0;
}
OUTPUT:

Result:

The above program is executed Successfully.


2)Write a program using the I/O system calls of UNIX operating system: open, read,
write, close.

AIM:

To implement the program using input and output system calls of unix operating system.

ALGORITHM:

STEP1: Declare variables n, fd and an array buff with size 25.


STEP2: Get text from the user and assign it to variable n.
STEP3: Open the text file on the variable fd.
STEP4: Write the text got from the user at the file opened at variable fd.
STEP5: Close the file opened at fd.

Coding:

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>

int main()
{
int n, fd;
char buff[50];
printf("Enter text to write in the file:\n");
n = read(0, buff, sizeof(buff));
fd = open("A.txt", O_CREAT | O_RDWR, 0777);
if (fd < 0) {
perror("File open error"); // Error handling in case the file couldn't be opened
return 1;
}write(fd, buff, n);
write(1, buff, n);
close(fd);
return 0;
}
Output:

Result:

The above program has been executed and output has been verified.
Experiment No: 4 Implementation of CPU Scheduling Algorithms
Date :

i)FIRST COME FIRST SERVE (FCFS) PROCESS SCHEDULING

AIM:

The program to perform scheduling for the processes using First Come First
Serve(FCFS) algorithm.

ALGORITHM:

1. Create the number of process.


2. Get the ID and Service time for each process.
3. Initially, waiting time of first process is zero and Total time for the first
process is the starting time of that process.
4. Calculate the Total time and Processing time for the remaining processes.
5. Waiting time of one process is the Total time of the previous process.
6. Total time of process is calculated by adding Waiting time and Service time.
7. Total waiting time is calculated by adding the waiting time for lack process.
8. Total turnaround time is calculated by adding all total time of each process.
9. Calculate Average waiting time by dividing the total waiting time by total
number of process.
10. Calculate Average turnaround time by dividing the total time by the number of
process.
11. Display the result.
PROGRAM:

#include<stdio.h>
int main()
{
int bt[10]={0},wt[10]={0},ct[10]={0};
float at[10]={0},tat[10]={0};
int n,sum=0;
float totalTAT=0,totalWT=0;

printf("___FCFS CPU SCHEDULING___");


printf("\n\nEnter number of process");
scanf("%d",&n);
printf("Enter arrival time and burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of process[%d]",i+1);
scanf("%f",&at[i]);
printf("Burst time of process[%d] ",i+1);
scanf("%d",&bt[i]);
printf("\n");
}
for(int j=0;j<n;j++)
{
sum+=bt[j];
ct[j]+=sum;
}
for( int k=0;k<n;k++)
{
tat[k]=ct[k]-at[k];
totalTAT+=tat[k];
}
for(int k=0;k<n;k++)
{
wt[k]=tat[k]-bt[k];
totalWT+=wt[k];
}
printf("Solution: \n\n");
printf("P\t AT\t BT\t CT\t TAT\t WT\t\n\n");
for(int i=0;i<n;i++)
{
printf("P%d\t %.2f\t %d\t %d\t %.2f\t %d\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\n\nAverage Turnaround time = %f\n",totalTAT/n);

printf("Average WT = %f\n\n",totalWT/n);
return 0;
}
COMMANDS:
skcet@cse:~$ gedit FCFS.c
skcet@cse:~$ cc FCFS.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:

Thus the C program to implement First Come First Serve (FCFS) scheduling
algorithm was done and the turnaround time and waiting time was displayed.
ii)SHORTEST JOB FIRST (SJF) PROCESS SCHEDULING

AIM:

The program to perform scheduling for the processes using Shortest Job First(SJF)
algorithm.

ALGORITHM:

1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n).
3. Obtain btime for each process.
4. Sort the processes according to their btime in ascending order.
a. If two process have same btime, then FCFS is used to resolve the tie.
5. The wtime for first process is 0.
6. Compute wtime and ttime for each process as:
a. wtime i+1= wtime i+ btime i b. ttime i = wtime i + btime i
7. Compute average waiting time awat and average turnaround time atur.
8. Display btime,ttime and wtime for each process.
9. Display GANTT chart for the above scheduling.
10. Display awat and atur.
11. Stop.
PROGRAM:

#include<stdio.h>
int main()
{
int A[100][4];
int i,j,n,total=0,index,temp;
float avg_wt,avg_tat;
printf("Enter number of process: ");
scanf("%d",&n);
printf("Enter Burst Time:\n");
for(i=0;i<n;i++){
printf("P%d: ",i+1);
scanf("%d",&A[i][1]);
A[i][0]=i+1;
}

for(i=0;i<n;i++){
index=i;
for(j=i+1;j<n;j++)
if(A[j][1]<A[index][1]);
index=j;
temp=A[i][1];
A[i][1]=A[index][1];
A[index][1]=temp;
temp=A[i][0];
A[i][0]=A[index][0];
A[index][0]=temp;
}
A[0][2]=0;
for(i=1;i<n;i++){
A[i][2]=0;
for(j=0;j<i;j++)
A[i][2]+=A[j][1];
total+=A[i][2];
}
avg_wt=(float)total/n;
total=0;
printf("P BT WT TAT\n");
for(i=0;i<n;i++){
A[i][1],A[i][1]+A[i][3];
total+=A[i][3];
printf("P%d %d %d %d\n",A[i][0],A[i][1],A[i][2],A[i][3]);
}
avg_tat=(float)total/n;
printf("Average Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f",avg_tat);
}

COMMANDS:
skcet@cse:~$ gedit SJF.c
skcet@cse:~$ cc SJF.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:

Thus the C program to implement Shortest Job First (SJF) scheduling algorithm was
done and the turnaround time and waiting time was displayed.
iii)ROUND ROBIN (RR) PROCESS SCHEDULING

AIM:

The program to perform scheduling for the processes using Round Robin (RR)
algorithm.

ALGORITHM:

1. Initialize all the structure elements


2. Receive inputs from the user to fill process id,burst time and arrival time.
3. Calculate the waiting time for all the process id.
i) The waiting time for first instance of a process is
calculated as: a[i].waittime=count + a[i].arrivt

ii) The waiting time for the rest of the instances of the process is calculated as:
a) If the time quantum is greater than the remaining burst time then
waiting time is calculated as:
a[i].waittime=count + tq
b) Else if the time quantum is greater than the remaining burst
time then waiting
time is calculated as:
a[i].waittime=count - remaining burst time
4. Calculate the average waiting time and average turnaround time
5. Print the results of the step 4.
PROGRAM:

#include<stdio.h>
void main()
{
int i,NDP,sum=0,count=0,y,quant,wt=0,tat=0,at[10],bt[10],temp[10];
float avg_wt,avg_tat;
printf("Total number of process int the system: ");
scanf("%d",&NDP);

y=NDP;
for(i=0;i<NDP;i++)
{
printf("\nEnter the Arrival and Burst time of the Process[%d]\n",i+1);
printf("Arrival time is: \t");
scanf("%d",&at[i]);
printf("\nBurst time is : \t");
scanf("%d",&bt[i]);
temp[i]=bt[i];
}
printf("Enter the Time Quantum for the process:\t");
scanf("%d",&quant);
printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting time ");
for(sum=0,i=0;y!=0;){
if(temp[i]<=quant&&temp[i]>0)
{
sum=sum+temp[i];
temp[i]=0;
count=1;
}
else if(temp[i]>0){
temp[i]=temp[i]-quant;
sum=sum+quant;
}

if(temp[i]==0&&count==1)
{
y--;
printf("\nProcess NO[%d] \t\t %d\t\t\t\t %d\t\t\t %d",i+1,bt[i],sum-at[i],sum-at[i]-bt[i]);
wt=wt+sum-at[i]-bt[i];
tat=tat+sum-at[i];
count=0;
}if(i==NDP-1)
i=0;
else if(at[i+1]<=sum)
i++;
else
i=0;
}
avg_wt=wt*1.0/NDP;
avg_tat=tat*1.0/NDP;
printf("\n Average Waiting Time: \t%f",avg_wt);
printf("\n Average Waiting Time: \t%f",avg_tat);
}
COMMANDS:
skcet@cse:~$ gedit roundRobin.c
skcet@cse:~$ cc roundRobin.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:
Thus the C program to implement Round Robin(RR) scheduling algorithm was done
and the turnaround time and waiting time was displayed.
Experiment No: 5 DINING PHILOSOPER ALGORITHM
Date :

AIM:

To write a C Program for the Implementation of Dining Philosopher Algorithm.

ALGORITHM:

1. Initialize the semaphores for each fork to 1 (indicating that they are available).
2. Initialize a binary semaphore (mutex) to 1 to ensure that only one philosopher can
attempt to pick up a fork at a time.
3. For each philosopher process, create a separate thread that executes the following
code:
While true:
Think for a random amount of time.
Acquire the mutex semaphore to ensure that only one philosopher can attempt
to pick up a fork at a time.
Attempt to acquire the semaphore for the fork to the left.
If successful, attempt to acquire the semaphore for the fork to the right.
If both forks are acquired successfully, eat for a random amount of time and then
release both semaphores.
If not successful in acquiring both forks, release the semaphore for the fork to the left
(if acquired) and then release the mutex semaphore and go back to thinking.
4. Run the philosopher threads concurrently.
PROGRAM:

#include<stdio.h>
#define n 4
int compltedPhilo = 0,i;
struct fork{
int taken;
}ForkAvil[n];
struct philosp{
int left;
int right;

}Philostatus[n];
void goForDinner(int philID){
if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
printf("Philosopher %d completed his dinner\n",philID+1);
else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
printf("Philosopher %d completed his dinner\n",philID+1);
Philostatus[philID].left = Philostatus[philID].right = 10;
int otherFork = philID-1;
if(otherFork== -1)
otherFork=(n-1);
ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0;
printf("Philosopher %d released fork %d and fork
%d\n",philID+1,philID+1,otherFork+1);
compltedPhilo++;
}
else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){
if(philID==(n-1)){
if(ForkAvil[philID].taken==0){
ForkAvil[philID].taken = Philostatus[philID].right = 1;
printf("Fork %d taken by philosopher %d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID+1);
}
}else{
int dupphilID = philID;
philID-=1;
if(philID== -1)
philID=(n-1);
if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[dupphilID].right = 1;
printf("Fork %d taken by Philosopher %d\n",philID+1,dupphilID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",dupphilID+1,philID+1);
}
}

}
else if(Philostatus[philID].left==0){
if(philID==(n-1)){
if(ForkAvil[philID-1].taken==0){
ForkAvil[philID-1].taken = Philostatus[philID].left = 1;
printf("Fork %d taken by philosopher %d\n",philID,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID);
}
}else{
if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[philID].left = 1;
printf("Fork %d taken by Philosopher %d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",philID+1,philID+1);
}
}
}else{}
}
int main(){
for(i=0;i<n;i++)
ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;
while(compltedPhilo<n){
for(i=0;i<n;i++)
goForDinner(i);
printf("\nTill now num of philosophers completed dinner are %d\n\n",compltedPhilo);
}
return 0;
}

COMMANDS:

skcet@cse:~$ gedit roundRobin.c


skcet@cse:~$ cc dpp.c
skcet@cse:~$ ./a.out
OUTPUT:

RESULT:

Thus the C program to implement the dining philosopher’s problem was implemented
Successfully.
Experiment No: 6 BANKER’S ALGORTIHM
Date:

AIM:

To implement of banker’s algorithm for deadlock avoidance using C.

ALGORITHM:

1. 1) Assume Work and Finish are two vectors, each with lengths of m and n.
2. Initialize: Work = Available
3. Finish[i] is false when i=1, 2, 3, 4...n
4. 2) Find an I such that both
5. a) Finish[i] = false
6. b) Needi <= Work
7. if such an I does not exist. goto step (4)
8. 3) Work = Work + Allocation[i]
9. Finish[i] = true
10. go to step (2)
11. 4) If Finish[i] = true for each and every i
12. then system is in a secure state.
13. 1) Proceed to step 2 if Requesti >= Needi; otherwise, report an error condition
because the process has made more claims than it can handle.
14. 2) Proceed to step (3) if Requesti <= Accessible; otherwise, Pi will have to wait
since the resources are not available.
15. 3) Change the state in such a way that the system appears to have given Pi the
required resources:
16. Requested - Available = Available
17. Allocationi = Allocationi + Requesti
18. Needi = Needi – Requesti
PROGRAM:

#include<stdio.h>
int main()
{
int n,m,i,j,k;
n=5;

m=3;
int alloc[5][3]={{0,1,0},{2,0,0},{3,0,2},{2,1,2},{0,0,2}};
int max[5][3]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
int avail[3]={3,3,2};
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 folowing system is not safe");
break;
}
}
if(flag==1){
printf("Following is the SAFE Sequence\n");
for(i=0;i<n;i++)
printf(" P%d ->",ans[i]);
printf(" P%d",ans[n-1]);
}
return 0;
}
COMMANDS:

skcet@cse:~$ gedit BA.c


skcet@cse:~$ cc BA.c
skcet@cse:~$ ./a.out

OUTPUT:

RESULT:
Thus the C program to implement the banker’s algorithm for deadlock avoidance
was implemented successfully.
Experiment No: 7
Date :

MEMORY ALLOCATION AND


MANAGEMENT TECHNIQUES

i)FIRST FIT MEMORY MANAGEMENT

AIM:

The program to implement the First Fit memory management strategy.

ALGORITHM:

1. Input memory blocks with size and processes with size.


2. Initialize all memory blocks as free.
3. Start by picking each process and check if it can
4. be assigned to current block.
5. If size-of-process <= size-of-block if yes, then
6. assign and check for next process.
7. If not, then keep checking the further blocks.
PROGRAM:

#include<stdio.h>
#define max 25
void main(){
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];int flag,flagn[max],fragi = 0,fragx = 0;
printf("\n___First Fit___\n");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of Process:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++) {

printf("Block %d:",i);
scanf("%d",&b[i]);
ff[i] = i;
}
printf("Enter the size of the Processes :-\n");
for(i=1;i<=nf;i++) {
printf("Process %d:",i);
scanf("%d",&f[i]);
}
int x = 1;
printf("\n\nProcess_No\tProcess_Size\tBlock_No\tBlock_Size\tFragment\n");
for(i=1;i<=nf;i++){
flag = 1;
for(j=x;j<=nb;j++){
if(f[i] <= b[j]){
flagn[j] = 1;
printf("%-15d\t%-15d\t%-15d\t%-15d\t",i, f[i],ff[j],b[j]);
b[j] = b[j] - f[i];
fragi = fragi + b[j];
printf("%-15d\n",b[j]);
break;
}else{
flagn[j] = 0;
x = 1;
flag++;
}}
if(flag > nb)
printf("%-15d\t%-15d\t%-15s\t%-15s\t%-15s\n",i,f[i],"Has to wait...","...","...");
}}

COMMANDS:

skcet@cse:~$ gedit firstfit.c


skcet@cse:~$ cc firstfit.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:
Thus the C program to implement the first fit memory management scheme is
successful.
ii)BEST FIT MEMORY MANAGEMENT

AIM:

The program to implement the Best Fit memory management strategy.

ALGORITHM:

1. Input memory blocks and processes with sizes.


2. Initialize all memory blocks as free.
3. Start by picking each process and find the minimum block size that can be
assigned to current process i.e., find min (bock Size [1], block Size [2],.....block
Size[n]) > process Size[current], if found then assign it to the current process.
4. If not, then leave that process and keep checking the further processes.

PROGRAM:

#include<stdio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max],fragi=0;
printf("\n___Best Fit___\n");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("\nEnter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++){printf("Block %d:",i);
scanf("%d",&b[i]);
ff[i]=i;
}
printf("\nEnter the size of the processors :-\n");
for(i=1;i<=nf;i++){
printf("Process %d:",i);
scanf("%d",&f[i]);

}
int y,m,z,temp1,flag;
for(y=1;y<=nb;y++)
{
for(z=y;z<=nb;z++)
{
if(b[y]>b[z])
{
temp=b[y];
b[y]=b[z];
b[z]=temp;
temp1=ff[y];
ff[y]=ff[z];
ff[z]=temp1;
}
}
}
int flagn[max];
int fragx=0;
printf("\n\nProcess_No\tProcess_Size\tBlock_No\tBlock_Size\tFragment\n");
for(i=1;i<=nf;i++)
{
flag=1;
for(j=1;j<=nb;j++)
{
if(f[i]<=b[j]){
flagn[j]=1;
printf("%-15d\t%-15d\t%-15d\t%-15d\t",i,f[i],ff[j],b[j]);
b[j]=b[j]-f[i];
fragi=fragi+b[j];
printf("%-15d\n",b[j]);
break;
}
else

{
flagn[j]=0;
flag++;
}
}
if(flag>nb)
printf("%-15d\t%-15d\t%-15s\t%-15s\t%-15s\n",i,f[i],"Has to wait..","..","..");
}
}

COMMANDS:

skcet@cse:~$ gedit bestfit.c


skcet@cse:~$ cc bestfit.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:

Thus the C program to implement the best fit memory management scheme is
successful.
iii)WORST FIT MEMORY MANAGEMENT

AIM:

The program to implement the Worst First memory management strategy.

ALGORITHM:

1. Input memory blocks and processes with sizes.


2. Initialize all memory blocks as free.
3. Start by picking each process and find the maximum block size that can be
assigned to current process i.e., find max (bock Size [1], block Size [2],.....block
Size[n]) > process Size[current], if found then assign it to the current process.
4. If not then leave that process and keep checking the further processes.

PROGRAM:

#include<stdio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
int flag,fragi=0;
printf("\n__Worst Fit__\n");
printf("\nEnter the number of memory blocks:");
scanf("%d",&nb);
printf("Enter the number of Process:");
scanf("%d",&nf);
printf("\nEnter the size of the memory blocks:\n");
for(int i=1;i<=nb;i++)
{
printf("Block %d: ",i);
scanf("%d",&b[i]);
ff[i]=i;
}
printf("Enter the size of the processes :\n");

for(i=1;i<=nf;i++)
{
printf("Process %d: ",i);
scanf("%d",&f[i]);
}
int y,z,temp1;
for(y=1;y<=nb;y++)
{
for(z=y;z<=nb;z++)
{
if(b[y]<b[z])
{
temp=b[y];
b[y]=b[z];
b[z]=temp;
temp1=ff[y];
ff[y]=ff[z];
ff[z]=temp1;
}
}
}
int flagn[max];
int fragx=0;
printf("\n\nProcess No\tProcess Size\tMemory No\tMemory Size\tRemaining\n");
for(i=1;i<=nf;i++)
{
flag=1;
for(int j=1;j<=nb;j++)
{
if(f[i]<=b[j])
{flagn[j]=1;
printf("%-15d\t%-15d\t%-15d\t%-15d\t",i,f[i],ff[j],b[j]);
b[j]=b[j]-f[i];
fragi=fragi+b[j];

printf("%-15d\n",b[j]);
break;}
else
{flagn[j]=0;
flag++;
}
}
if(flag>nb)
printf("%-15d\t%-15d\t%-15s\t%-15s\t%-15s\n",i,f[i],"Has to wait..","..","..");}}

COMMANDS:

skcet@cse:~$ gedit *worstfit.c


skcet@cse:~$ cc *worstfit.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:

Thus the C program to implement the worst fit memory management scheme is
successful.
Experiment No: 8
Date:

IMPLEMENTATION OF PAGE REPLACEMENT TECHNIQUES

i)FIRST IN FIRST OUT(FIFO) PAGE REPLACEMENT

AIM:

The program to implement first in first out page replacement for replacing the pages
in the virtual memory and calculating the number of page faults.

ALGORITHM:

1. Start the program


2. Read the block size and compare with the pages in the block
3. When matches found in the block set hit to one, when the page is not present in the
block increment page fault count by one
4. Store the page in the block by getting index of the block through mod function
5. Display the number of page fault count, after reading new page the contents of the
block will be displayed
6. End the process.
PROGRAM:

#include<stdio.h>
int main()
{
int incomingStream[] = {4, 1, 2, 4, 5};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;

pages = sizeof(incomingStream)/sizeof(incomingStream[0]);

printf("Incoming \t Frame 1 \t Frame 2 \t Frame 3");


int temp[frames];
for(m = 0; m < frames; m++)
{

temp[m] = -1;
}

for(m = 0; m < pages; m++)


{
s = 0;

for(n = 0; n < frames; n++)


{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}
pageFaults++;

if((pageFaults <= frames) && (s == 0))


{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}
printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");

}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}

COMMANDS:

skcet@cse:~$ gedit fifo.c


skcet@cse:~$ cc fifo.c
skcet@cse:~$ ./a.out
OUTPUT:

RESULT:

Thus the C program to implement FIFO page replacement was implemented


successfully and the output was verified.
ii)LEAST RECENTLY USED(LRU) PAGE REPLACEMENT

AIM:

The program to implement Least Recently Used page replacement for replacing the
pages in the virtual memory and calculating the number of page faults.

ALGORITHM:

1. Start the process


2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process

PROGRAM:

#include<stdio.h>
int main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{

c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{

for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);
}

COMMANDS:

skcet@cse:~$ gedit lru.c


skcet@cse:~$ cc lru.c
skcet@cse:~$ ./a.out
INPUT:

OUTPUT:

RESULT:

Thus the C program to implement LRU page replacement was implemented


successfully and the output was verified.
iii)OPTIMAL PAGE REPLACEMENT ALGORITHM

AIM:

The program to implement optimal page replacement for replacing the pages in the
virtual memory and calculating the number of page faults.

ALGORITHM:

1. If referred page is already present, increment hit count.


2. If not present, find if a page that is never referenced in future.
3. If such a page exists, replace this page with new page.
4. If no such page exists, find a page that is referenced farthest in future.
5. Replace this page with new page.

PROGRAM:

#include<stdio.h>
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j,
k,
pos, max, faults = 0;

printf("Enter number of frames: ");


scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

printf("Enter page reference string: ");

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


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

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


frames[i] = -1;
}

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


flag1 = flag2 = 0;
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

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


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}

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


if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}

if(flag3 ==0){
max = temp[0];
pos = 0;

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


if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}

printf("\n");

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


printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}

COMMANDS:

skcet@cse:~$ gedit optimal.c


skcet@cse:~$ cc optimal.c
skcet@cse:~$ ./a.out

INPUT:
OUTPUT:

RESULT:

Thus the C program to implement Optimal page replacement was implemented


successfully and the output was verified.
Experiment No: 9 IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUES
Date :

i) Single level directory

AIM:

To write a C program to implement File Organization concept using the technique Single
level directory.

ALGORITHM:

Step-1: Start the program.


Step-2: Declare the count, file name, graphical interface.
Step-3: Read the number of files
Step-4: Read the file name
Step-5: Declare the root directory
Step-6: Using the file eclipse function define the files in a single level
Step-7: Display the files
Step-8: Stop the program

PROGRAM:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

struct {
char dname[10], fname[10][10];
int fcnt;
} dir;

void main() {
int i, ch;
char f[30];
dir.fcnt = 0;
printf("\nEnter name of directory: ");
scanf("%s", dir.dname);

while(1) {
printf("\n\n1. Create File\t2. Delete File\t3. Search File \n4. Display Files\t5.
Exit\nEnter your choice: ");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("\nEnter the name of the file: ");
scanf("%s", dir.fname[dir.fcnt]);
dir.fcnt++;
break;
case 2:
printf("\nEnter the name of the file: ");
scanf("%s", f);
for(i = 0; i < dir.fcnt; i++) {
if(strcmp(f, dir.fname[i]) == 0) {
printf(" %s is deleted", f);
strcpy(dir.fname[i], dir.fname[dir.fcnt-1]);
break;

}
}
if(i == dir.fcnt)
printf(" %s not found", f);
else
dir.fcnt--;
break;
case 3:
printf("\nEnter the name of the file to search: ");
scanf("%s", f);
for(i = 0; i < dir.fcnt; i++) {
if(strcmp(f, dir.fname[i]) == 0) {
printf(" %s is found", f);
break;
}
}
if(i == dir.fcnt)
printf(" %s not found", f);
break;
case 4:
if(dir.fcnt == 0)
printf("\nDirectory Empty");
else {
printf("\nThe Files are: ");

for(i = 0; i < dir.fcnt; i++)


printf("%s\n", dir.fname[i]);
}
break;
default:
exit(0);
}
}
}

OUTPUT:

RESULT:

Thus the above program has been executed successfully.


IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUES

ii)Two Level Directory

AIM:

To write a C program to implement File Organization concept using the technique Two
Level Directory.

ALGORITHM:

Step-1: Start the program.


Step-2: Declare the count, file name, graphical interface.
Step-3: Read the number of files
Step-4: Read the file name
Step-5: Declare the root directory
Step-6: Using the file eclipse function define the files in a single level
Step-7: Display the files
Step-8: Stop the program

PROGRAM:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct {
char dname[10], fname[10][10];
int fcnt;
} dir[10];
void main() {
int i, ch, dcnt, k;
char f[30], d[30];

dcnt = 0;

while (1) {
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\nEnter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("\nEnter name of directory: ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt = 0;
dcnt++;
printf("Directory created");
break;
case 2:
printf("\nEnter name of the directory: ");
scanf("%s", d);
for (i = 0; i < dcnt; i++) {
if (strcmp(d, dir[i].dname) == 0) {
printf("Enter name of the file: ");
scanf("%s", dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
break;

}
}
if (i == dcnt)
printf("Directory %s not found", d);
break;
case 3:
printf("\nEnter name of the directory: ");
scanf("%s", d);
for (i = 0; i < dcnt; i++) {
if (strcmp(d, dir[i].dname) == 0) {
printf("Enter name of the file: ");
scanf("%s", f);
for (k = 0; k < dir[i].fcnt; k++) {
if (strcmp(f, dir[i].fname[k]) == 0) {
printf("File %s is deleted", f);
dir[i].fcnt--;
strcpy(dir[i].fname[k], dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found", f);
goto jmp;
}
}

printf("Directory %s not found", d);


jmp: break;
case 4:
printf("\nEnter name of the directory: ");
scanf("%s", d);
for (i = 0; i < dcnt; i++) {
if (strcmp(d, dir[i].dname) == 0) {
printf("Enter the name of the file: ");
scanf("%s", f);
for (k = 0; k < dir[i].fcnt; k++) {
if (strcmp(f, dir[i].fname[k]) == 0) {
printf("File %s is found", f);
goto jmp1;
}
}
printf("File %s not found", f);
goto jmp1;
}
}
printf("Directory %s not found", d);
jmp1: break;
case 5:
if (dcnt == 0)
printf("\nNo Directory's ");

else {
printf("\nDirectory\tFiles");
for (i = 0; i < dcnt; i++) {
printf("\n%s\t\t", dir[i].dname);
for (k = 0; k < dir[i].fcnt; k++)
printf("\t%s", dir[i].fname[k]);
}
}
break;
default:
exit(0);
}
}
}
OUTPUT:

Result:

Thus the above program has been executed successfully.


Experiment No: 10 IMPLEMENTATION OF DISK SHEDULING
Date :

i)FCFS SCHEDULING

AIM:

To illustrate the First Come First Served (FCFS) disk scheduling with the
help of C program.

ALGORITHM:

1. Start.
2. Declare the required variables.
3. Get the size of the queue and enter the queue elements.
4. Get the initial position from the user.
5. Calculate diff =abs(queue[j]-queue[j+1]) and seek+=diff using for loop.
6. Print the number of cylinders.
7. Stop.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
// logic for FCFS disk scheduling
for(i=0;i<n;i++)

{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
printf("Total head moment is %d",TotalHeadMoment);
return 0;
}
OUTPUT:

RESULT:

The program to illustrate FCFS scheduling in c language is verified and


executed successfully.
IMPLEMENTATION OF DISK SHEDULING

ii)SSTF SCHEDULING

AIM:

To illustrate the Shortest seek time first (SSTF) disk scheduling with the
help of C program.

ALGORITHM:

1. Start.
2. Define a structure.
3. Declare the required variables.
4. Get the size of queue, queue elements, initial position from the user.
5. Select the request which is closest to the current position before
moving from that position to service other requests.
6. Print the number of cylinders.
7. Stop.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial,count=0;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
// logic for SSTF disk scheduling
while(count!=n){
int min=1000,d,index;

for(i=0;i<n;i++){
d=abs(RQ[i]-initial);

if(min>d){
min=d;
index=i;
}}
TotalHeadMoment=TotalHeadMoment+min;
initial=RQ[index];
RQ[index]=1000;
count++;
}
printf("Total head moment is %d",TotalHeadMoment);
return 0;
}
OUTPUT:

RESULT:

The program to illustrate SSTF scheduling in c language is verified and executed


successfully.

You might also like