DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
LABORATORY MANUAL
Sub.Code
: CS3461 & AL3452
Sub.Name
: OPERATING SYSTEMS LABORATOTY
Regulation
: R2021
Year/Sem/Branch
: II/IV/CSE & CSE (AIML)
Prepared By,
Verified by,
Approved By,
Dr.S.J.Subhashini
Dr.C.Callins Christiyana
Dr.S.Durairaj
HoD/CSE
Principal
Associate Professor/CSE
1
OPERATING SYSTEM LABORATORY
INDEX
Sl.No
List of Experiments
Page
No
1
Installation of Operating system : Windows/ Linux
3
2
Illustration of UNIX commands and Shell Programming
4
3
4
Implementation of Process Management using System
Calls : Fork, Exec, Getpid, Exit, Wait, Close.
Implementation of various CPU Scheduling Algorithms
a.FCFS b.SJF C. Priority Scheduling d)Round Robin
10
13
5
Illustration of Inter Process communication strategy
24
6
Implementation of Mutual Exclusion by Semaphores
26
7
Implementation of Bankers Algorithm
29
8
Implementation of Deadlock Detection Algorithm
34
9
Implementation of Threading
38
10
Implementation of paging Technique.
40
11
Implementation of Memory Allocation Methods
a. First Fit b. Worst Fit c. Best Fit
43
Implementation of various Page Replacement
12
Algorithms
a.FIFO
13
14
15
16
49
b. LRU C. LFU
Implementation of various File Organization Techniques
a. Single Level b. Two Level
Implementation File Allocation Strategies.
a. Sequential b. Indexed c. Linked
Implementation of various disk scheduling algorithms
a. FCFS b. SSTF C.SCAN d. C-SCAN
Installation of any guest operating system like Linux
using VMware.
2
56
63
69
78
Installation of Operating System: Windows / Linux
Exp.no: 1
Date:
Aim:
To Install the Operating system: Windows/ Linux.
Proedure:
1. Obtain the installation media (e.g. a Windows installation USB drive or DVD).
2. Connect the installation media to your computer and restart the machine.
3. Boot the machine from the installation media by changing the boot order in the BIOS or UEFI settings.
4. Follow the on-screen instructions to install Windows. You will need to accept the license agreement, select
the installation type (e.g. custom or upgrade), choose the installation location (e.g. which hard drive and
partition), and configure basic settings such as language, time and currency format, and keyboard input
method.
5. Once the installation is complete, the machine will restart and guide you through the initial setup process.
Sample Viva Questions
1. What is Operating System?
2. List the Services of operating system function.
3. What are the objectives of operating systems?
4. Can you List out name of Operating system?
5. What is system boot?
3
Illustration of UNIX commands and Shell Programming
Exp.no: 2
Date:
Aim:
To Illustrate UNIX commands and Shell Programming.
UNIX General Commands:
1. Date Command:
This command is used to display the current data and time.
Syntax:
$date
2. Calender Command:
This command is used to display the calendar of the year or the particular month of
calendar year.
Syntax:
a. $cal <year>
b. $cal <month> <year>
Here the first syntax gives the entire calendar for given year & the second Syntax gives
the calendar of reserved month of that year.
3. Echo Command:
This command is used to print the arguments on the screen.
Syntax:
$echo <text>
4. Banner Command:
It is used to display the text in ‘#’ symbol .It displays the text in the form of a banner.
Syntax :
$banner <arguments>
5.’who’ Command:
It is used to display who are the users connected to our computer currently.
Syntax:
$who
6.’who am i’ Command:
Display the details of the current working directory.
Syntax:
$who am i
4
7.’tty’ Command:
It will display the terminal name.
Syntax:
$tty
8.’CLEAR’ Command:
It is used to clear the screen.
Syntax:
$clear
9.’MAN’ Command:
It helps us to know about the particular command and its options & working. It is like
‘help’ command in windows.
Syntax:
$man <command name>
10. LIST Command:
It is used to list all the contents in the current working directory.
Syntax:
$ ls – options <arguments>
If the command does not contain any argument means it is working in the Current
directory.
Options:
a– used to list all the files including the hidden files.
c– list all the files columnwise.
d- list all the directories.
m- list the files separated by commas.
p- list files include ‘/’ to all the directories.
r- list the files in reverse alphabetical order.
f- list the files based on the list modification date.
x-list in column wise sorted order.
Directory Related Commands:
1. Present Working Directory Command:
To print the complete path of the current working directory.
Syntax:
$pwd
2. MKDIR Command:
To create or make a new directory in a current directory.
5
Syntax:
$mkdir <directory name>
3. CD Command:
To change or move the directory to the mentioned directory .
Syntax :
$cd <directory name>.
4. RMDIR Command:
To remove a directory in the current directory & not the current directory itself.
Syntax:
$rmdir <directory name>
File Related Commands:
1. Create a File:
To create a new file in the current directory we use CAT command.
Syntax:
$cat > filename.
2. Display a File:
To display the content of file mentioned we use CAT command without ‘>’ operator.
Syntax:
$cat filename.
3. Copying Contents:
To copy the content of one file with another. If file doesnot exist, a new file is created
and if the file exists with some data then it is overwritten.
Syntax :
$ cat <source filename> >> <destination filename>
4. Sorting a File:
To sort the contents in alphabetical order in reverse order.
Syntax:
$sort <filename >
Option: $ sort –r <filename>
5. Copying contents from one file to another:
To copy the contents from source to destination file so that both contents are same.
Syntax: $cp <source filename> <destination filename>
$cp <source filename path > <destination filename path>
6. Move Command:
To completely move the contents from source file to destination file and to remove the
6
source file.
Syntax:
$ mv <source filename> <destination filename>
7. Remove Command:
To permanently remove the file we use this command.
Syntax:
$rm <filename>
8. Word Command:
To list the content count of no of lines, words, characters.
Syntax:
$wc<filename>
Shell Programming
Aim:
To write the shell programs for the following
a) Find the greatest numbers
b) Sum of ‘n’ numbers
c) Swapping of 2 numbers
d) Checking whether the number is positive or negative
a. Find the greatest numbers
Program:
echo “Enter 2 numbers”
read a b
if [ $a –gt $b ]
then
echo “$a is greater”
else
echo “$b is greater”
fi
Output:
Enter 2 numbers
37
7 is greater
b. Sum of n numbers:
Program:
echo "Enter limit"
7
read n
i=1
sum=0
while [ $i -le $n ]
do
let sum=$sum+$i
let i=$i+1
done
echo "The sum of $n numbers is $sum"
Output:
Enter limit
5
The sum of 5 numbers is 15
c. Swapping of two numbers:
Program:
echo "Enter two numbers"
read a b
t=$a
a=$b
b=$t
echo "a=$a b=$b"
Output:
Enter two numbers
47
a=7
b=4
d. Checking the number is positive or negative:
Program:
echo "Enter a number"
read a
if [ $a -ge 0 ]
then
echo "$a is positive"
else
echo "$a is negative"
8
fi
Output:
Enter a number
5
5 is positive
Sample Viva questions:
1. What is Shell Scripting?
2. List some of the common and most widely used UNIX commands
3. What are Shell Variable
Augmented Questions :
1. Write shell script fori. Showing the count of users logged in.
ii. Printing Column list of files in your home directory.
iii. Listing your job with below normal priority.
iv. Continue running your job after logging out.
v. Printing end of a Glossary file in reverse order using array
9
Implementation of Process Management using System Calls.
Exp.no: 3
Date:
Aim:
To write a program to implement the process management using the following system calls fork, exec,
getpid, exit, wait, close.
Algorithm:
1: Start the program.
2: Read the input from command line.
3: fork() is used to create a new child process.
4: getpid() is used to retrieve the process ID of the current process.
5: execvp() is used to replace the current process image with a new process image specified by the given
command. (/bin/ls -l)
6: wait() is used in the parent process to wait for the child process to finish.
7: exit() is used to terminate the process.
8: Display the directory contents.
9: Stop the program.
Program:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t child_pid;
// Fork a child process
child_pid = fork();
if (child_pid < 0)
{
// Fork failed
perror("Fork failed");
return 1;
}
else if (child_pid == 0)
{
10
// This is the child process
printf("Child process: PID=%d\n", getpid());
// Execute a new program in the child process
execl("/bin/ls", "ls", "-l", NULL);
// exec only returns if an error occurs
perror("execl failed");
return 1;
}
else
{
// This is the parent process
printf("Parent process: PID=%d\n", getpid());
// Wait for the child process to finish
wait(NULL);
printf("Child process finished.\n");
// Close resources if necessary
// close(file_descriptor);
}
// Exit parent process
return 0;
}
Sample Input and Output:
Parent process: PID=41
Child process: PID=42
----------Child process finished.
Sample Viva questions:
1. What is a zombie process?
2. What are the types of system calls in process management?
3. What is a process control block (PCB)?
11
Augmented Questions:
1. Write a program where you create multiple processes and adjust their priority using the nice() system call.
The objective is to see how the scheduler gives CPU time to processes with varying priority levels.
2. Write a program that continuously forks processes until the system becomes unresponsive. This experiment
helps you understand how system resources can be exhausted when processes are not managed properly.
This is often used in DoS (Denial of Service) attacks, but should be conducted with caution.
3. Create a set of processes that simulate different states such as running, sleeping, and waiting. Use system
calls like sleep(), wait(), and others to control the states. Monitor the transitions between these states.
12
Implementation of various CPU Scheduling Algorithms
Exp.no: 4
Date:
Aim:
To implement FCFS, SJF, Priority and Round robin scheduling algorithms using C.
4a.FCFS – First Come First Served
Algorithm:
1: Get the number of processes and burst time.
2: The process is executed in the order given by the user.
3: Calculate the waiting time and turn around time.
4: Display the gantt chart, avg waiting time and turn around time.
Program:
#include<stdio.h>
void main(int argc,char*argv[])
{
int
i,j=0,n,burst[10],wait[10],turn[1
0];
float w=0,t=0;
printf("Enter the no. of processes");
scanf("%d",&n);
burst[0]=0;
printf("Enter the burst time");
for(i=1;i<=n;i++)
{
scanf("%d",&burst[i]);
}
printf("\n\nGantt chart\n");
printf("\n \n");
for(i=1;i<=n;i++)
printf("\tP%d\t|",i);
printf("\n \n");
for(i=0;i<=n;i++)
13
{ j=j+burst[i];
wait[i+1]=j;
turn[i]=j;
printf("%d\t\t",j);
}
for(i=1;i<=n;i++)
w=w+wait[i];
for(i=0;i<=n;i++)
t=t+turn[i];
w=w/n;
t=t/n;
printf("\nAverage waiting time %0.2f",w);
printf("\nAverage turnaroundtime %0.2f",t);
}
31
Sample Input and Output:
Enter the number of processes: 4
Enter the burst time for each process: P1: 10 P2: 5 P3: 8 P4: 3
Gantt chart
P1 |P2 |P3 |P4 |
10 15 23 26
Average waiting time: 8.50
Average turnaround time: 15.25
4b.SJF (SHORTESTJOB FIRST)
Algorithm:
1: Get the number of processes and burst time.
2: Sort the process based on the burst time in ascending order.
3: Calculate the waiting time and turn around time.
4: Display the gantt chart,avg waiting time and turn around time.
Program:
#include<stdio.h>
void main(int argc,char *argv[])
{
int b[10],temp,i,j,n,wait[10],burst[10],turn[10];
float w=0,t=0;
14
printf("Enter the no. of processes");
scanf("%d",&n);
burst[0]=0;
b[0]=0;
printf("Enter the burst time");
for(i=1;i<=n;i++)
{
scanf("%d",&burst[i]);
} for(i=1;i<=n;i++)
b[i]=burst[i];
for(i=1;i<n;i++)
for(j=i+1;j<=n;j++)
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
printf("\nGantt chart");
printf("\n \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(b[i]==b[j])
printf("P%d|\t",j);
printf("\n \n");
32
j=0;
for(i=0;i<=n;i++)
{ j=j+b[i];
wait[i+1]=j;
turn[i]=j;
printf("%d\t",j);
}
for(i=1;i<=n;i++)
w=w+wait[i];
15
for(i=0;i<=n;i++)
t=t+turn[i];
w=w/n;
t=t/n;
printf("\nAverage waiting time is %0.2f",w);
printf("\nAverage turnaroundtime is %0.2f",t);
}
Sample Input and Output:
Enter the number of processes: 4 Enter the burst time for each process: P1: 6 P2: 8 P3: 7 P4: 3
Gantt chart
P4| P1| P3| P2|
3
9
16
24
Average waiting time is 5.00
Average turnaround time is 9.00
4c) Priority Scheduling
Algorithm:
1: Get the number of processes, priority and burst time.
2: Sort the process based on the priority in ascending order
3: Calculate the waiting time and turn around time.
4: Display the gantt chart, avg waiting time and turn around time.
Program:
#include <stdio.h>
struct process
{
int id;
// Process ID
int bt;
// Burst Time
int wt;
// Waiting Time
int tat;
// Turnaround Time
int priority; // Priority
};
void findWaitingTime(struct process proc[], int n)
{
proc[0].wt = 0; // Waiting time for the first process is 0
// Calculate waiting time for each process
16
for (int i = 1; i < n; i++)
{
proc[i].wt = proc[i - 1].bt + proc[i - 1].wt;
}
}
void findTurnaroundTime(struct process proc[], int n)
{
// Turnaround Time = Waiting Time + Burst Time
for (int i = 0; i < n; i++) {
proc[i].tat = proc[i].wt + proc[i].bt;
}
}
void findAverageTimes(struct process proc[], int n)
{
int totalWT = 0, totalTAT = 0;
// Calculate total waiting time and turnaround time
for (int i = 0; i < n; i++) {
totalWT += proc[i].wt;
totalTAT += proc[i].tat;
}
// Print average waiting time and turnaround time
printf("\nAverage Waiting Time: %.2f", (float)totalWT / n);
printf("\nAverage Turnaround Time: %.2f", (float)totalTAT / n);
}
void priorityScheduling(struct process proc[], int n)
{
// Sorting processes by priority
struct process temp;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (proc[i].priority > proc[j].priority)
{
temp = proc[i];
17
proc[i] = proc[j];
proc[j] = temp;
}
}
}
// Find waiting time and turnaround time
findWaitingTime(proc, n);
findTurnaroundTime(proc, n);
// Display the process details
printf("\nProcess ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\n", proc[i].id, proc[i].bt, proc[i].priority, proc[i].wt, proc[i].tat);
}
// Calculate and print average times
findAverageTimes(proc, n);
}
int main()
{
int n;
// Input the number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
struct process proc[n];
// Input the burst time and priority for each process
for (int i = 0; i < n; i++)
{
proc[i].id = i + 1; // Assign process ID
printf("\nEnter Burst Time and Priority for Process P%d:\n", i + 1);
printf("Burst Time: ");
scanf("%d", &proc[i].bt);
printf("Priority: ");
scanf("%d", &proc[i].priority);
}
// Call the priority scheduling function
18
priorityScheduling(proc, n);
return 0;
}
Sample Input and Output:
Enter the number of processes: 4
Enter Burst Time and Priority for Process P1:
Burst Time: 6
Priority: 3
Enter Burst Time and Priority for Process P2:
Burst Time: 8
Priority: 1
Enter Burst Time and Priority for Process P3:
Burst Time: 7
Priority: 4
Enter Burst Time and Priority for Process P4:
Burst Time: 3
Priority: 2
Process ID Burst Time
Priority Waiting Time Turnaround Time
P2
8
1
0
8
P4
3
2
8
11
P1
6
3
11
17
P3
7
4
17
24
Average Waiting Time: 9.00
Average Turnaround Time: 15.00
4d RR Scheduling (Round Robin)
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:
19
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 4.
Program:
#include <stdio.h>
void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum)
{
int rem_bt[n];
for (int i = 0; i < n; i++)
. {
rem_bt[i] = bt[i]; // Initialize remaining burst times
}
int time = 0; // Time tracker
while (1)
{
int done = 1;
for (int i = 0; i < n; i++)
{
if (rem_bt[i] > 0)
{
done = 0;
if (rem_bt[i] > quantum)
{
time += quantum;
rem_bt[i] -= quantum;
}
else
{
time += rem_bt[i];
wt[i] = time - bt[i]; // Waiting time = time spent - burst time
rem_bt[i] = 0; // Process completed
}
20
}
}
if (done == 1) {
break; // Exit when all processes are done
}
}
}
void findTurnaroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{
// Turnaround Time = Burst Time + Waiting Time
for (int i = 0; i < n; i++)
{
tat[i] = bt[i] + wt[i];
}
}
void findAverageTimes(int processes[], int n, int wt[], int tat[])
{
int total_wt = 0, total_tat = 0;
// Calculate total waiting time and turnaround time
for (int i = 0; i < n; i++)
{
total_wt += wt[i];
total_tat += tat[i];
}
// Print average waiting time and turnaround time
printf("\nAverage Waiting Time: %.2f", (float)total_wt / n);
printf("\nAverage Turnaround Time: %.2f", (float)total_tat / n);
}
void roundRobinScheduling(int processes[], int n, int bt[], int quantum)
{
int wt[n], tat[n];
// Find waiting time and turnaround time
findWaitingTime(processes, n, bt, wt, quantum);
findTurnaroundTime(processes, n, bt, wt, tat);
// Print process details
21
printf("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t%d\t\t%d\n", processes[i], bt[i], wt[i], tat[i]);
}
/ Calculate and print average times
findAverageTimes(processes, n, wt, tat);
}
int main()
{
int n, quantum;
// Input number of processes and time quantum
printf("Enter the number of processes: ");
scanf("%d", &n);
int processes[n], burst_time[n];
// Input burst time for each process
printf("Enter the burst time for each process:\n");
for (int i = 0; i < n; i++)
{
processes[i] = i + 1; // Assign process ID starting from 1
printf("P%d: ", i + 1);
scanf("%d", &burst_time[i]);
}
// Input time quantum for Round Robin scheduling
printf("Enter the time quantum: ");
scanf("%d", &quantum);
// Call the Round Robin scheduling function
roundRobinScheduling(processes, n, burst_time, quantum);
return 0;
}
Sample Input and Output:
Enter the number of processes: 4
Enter the burst time for each process:
P1: 5
P2: 9
22
P3: 6
P4: 7
Enter the time quantum: 4
Process ID Burst Time
Waiting Time Turnaround Time
1
5
6
11
2
9
12
21
3
6
11
17
4
7
13
20
Average Waiting Time: 10.50
Average Turnaround Time: 17.25
Sample Viva Questions:
1. Which CPU Scheduling Algorithm is best?
2. What is Starvation in the context of CPU Scheduling?
3. What is the difference between Pre-emptive and Non-Pre-emptive Scheduling Algorithms?
Augmented Questions:
1. Create a Gantt chart to visually represent process execution under SJF.
2. Implement a hybrid scheduling algorithm that combines multiple algorithms based on process type or time
of day.
23
Illustration of Inter Process Communication Strategy
Exp.no: 5
Date:
Aim:
To write a c program for inter process communication using shared memory.
Algorithm:
1: Create a child process using fork() command.
2: Create shared memory for parent process shmget() system call.
3: The current process write the content in shared memory using shmptr pointer.
4: Attach the same shared memory to the child process.
5: The data in shared memory is read by the child process using shmptr() pointer.
6: Detach and rebase the shared memory.
Program:
#include<stdio.h>
#include<sys/shm.h>
#include<sys/ipc.h>
int main()
{
int child,shmid,i;
char *shmptr;
child=fork();
if(!child)
{
shmid=shmget(2041,32,0666|IPC_CREAT);
shmptr=shmat(shmid,0,0);
printf("\n PARENT PROCESS WRITING \n");
for(i=0;i<10;i++)
{
shmptr[i]='a'+i;
putchar(shmptr[i]);
}
printf("\n\n %s",shmptr);
wait(NULL);
}
24
else
{
shmid=shmget(2041,32,0666);
shmptr=shmat(shmid,0,0);
printf("\n CHILD PROCESS READING\n");
for(i=0;i<10;i++)
putchar(shmptr[i]);
shmdt(NULL);
shmctl(shmid,IPC_RMID,NULL);
}
return 0
}
Sample Input and Output:
[root@local host~]# ./a.out
parent process writing
abcdefghij
child process reading
abcdefghij
Sample Viva Questions:
1.
What are the different types of IPC mechanisms?
2.
What is Shared Memory in IPC?
3.
What is the purpose of a Mutex in IPC?
Augmented Questions:
1.
Simulate a scenario with multiple processes (e.g., producers and consumers) accessing a shared
resource.
2.
Implement bi-directional communication between the parent and child processes using shared
memory.
25
Implementation of Mutual Exclusion by Semaphores
Exp.no: 6
Date:
Aim:
To Implement mutual exclusion by Semaphores
Algorithm:
1: Declare a semaphore variable mutex and a shared resource variable shared_resource.
2: Initialize the semaphore using the sem_init() function with a value of 1, indicating that only one thread
can access the critical section at a time.
3: Create several threads that will access the critical section of the code.
4: In each thread, loop through several iterations.
5: Call sem_wait() on the semaphore to wait for access to the critical section.
6: Read the value of the shared resource.
7: Modify the value of the shared resource.
8: Call sem_post() on the semaphore to release access to the critical section.
9: End the loop and the thread using pthread_exit().
10: Wait for all threads to finish using pthread_join().
11: Destroy the semaphore using sem_destroy().
Program:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
sem_t mutex;
int shared_resource = 0;
void *thread_function(void *arg)
{
int i, val;
long thread_id = (long)arg;
for (i = 0; i < 5; i++)
{
sem_wait(&mutex);
val = shared_resource;
printf("Thread %ld: Read %d from shared resource\n", thread_id, val);
26
val++;
printf("Thread %ld: Writing %d to shared resource\n", thread_id, val);
fflush(stdout);
shared_resource = val;
sem_post(&mutex);
}
pthread_exit(NULL);
}
int main()
{
pthread_t threads[3];
int i, ret;
sem_init(&mutex, 0, 1);
for (i = 0; i < 3; i++)
{
ret = pthread_create(&threads[i], NULL, thread_function, (void *)(long)i);
if (ret != 0)
{
perror("pthread_create failed");
return -1;
}
}
for (i = 0; i < 3; i++)
{
ret = pthread_join(threads[i], NULL);
if (ret != 0)
{
perror("pthread_join failed");
return -1;
}
}
sem_destroy(&mutex);
return 0;
}
27
Sample Input and Output:
Thread 0: Read 0 from shared resource
Thread 0: Writing 1 to shared resource
Thread 0: Read 1 from shared resource
Thread 0: Writing 2 to shared resource
Thread 0: Read 2 from shared resource
Thread 0: Writing 3 to shared resource
Thread 0: Read 3 from shared resource
Thread 0: Writing 4 to shared resource
Thread 0: Read 4 from shared resource
Thread 0: Writing 5 to shared resource
Thread 1: Read 5 from shared resource
Thread 1: Writing 6 to shared resource
Thread 1: Read 6 from shared resource
Thread 1: Writing 7 to shared resource
Thread 1: Read 7 from shared resource
Thread 1: Writing 8 to shared resource
Thread 1: Read 8 from shared resource
Thread 1: Writing 9 to shared resource
Thread 1: Read 9 from shared resource
Thread 1: Writing 10 to shared resource
Thread 2: Read 10 from shared resource
Thread 2: Writing 11 to shared resource
Thread 2: Read 11 from shared resource
Thread 2: Writing
Sample Viva Questions:
1. What is Mutual Exclusion?
2. What is the difference between Binary Semaphore and Counting Semaphore?
Augmented Questions:
1. Implement a program where multiple processes (or threads) try to access a shared resource (e.g., a file,
counter, or database) using a binary semaphore.
2. Implement a producer-consumer problem where a producer process generates data and stores it in a shared
buffer, while a consumer process retrieves data from the buffer.
28
Implementation of Bankers Algorithm
Exp.no: 7
Date:
Aim:
To write a C program to implement Bankers Algorithm to avoid Deadlock.
Algorithm:
1: Get the no of processes.
2: Get the process numbers.
3: Get the no of resources types and instances of it.
4: Get Max demand of each process of n x m matrices.
5: Get the n x m matrices the number of resources of each type currently allocated
to each process.
6: Calculate the n x m of the remaining resource need of each process.
7: Initialize work as available resource and array of finish to false.
8: Check the Needed resource is lesser than the available resource if not display the
System not in safe state and if it is lesser than system in safe state.
9: Initialize work as sum of work and allocation, check if array of finish is true go to
7 again if not go to step 8.
10: Check that request can be immediately granted.
11: If single request is lesser than or equal to available if true means arrive to new state.
12: Print the sequence if it is in safe state or print not in safe state.
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int p,r,m,z,k,buf,a[10],avail[10],max[10][10],alloc[10][10],need[10][10],i,j,top;
void get()
{
printf("\nENTER THE NUMBER OF PROCESSES:");
scanf("%d",&p);
printf("\nENTER THE NUMBER OF RESOURCE TYPES:");
scanf("%d",&r);
for(j=1;j<=r;j++)
{
29
printf("\nENTER THE NUMBER OF RESOURCES FOR TYPE %d : ",j);
scanf("%d",&avail[j]);
}
for(i=1;i<=p;i++)
{
printf("\nENTER THE MAXIMUM NUMBER OF RESOURCES REQUIRED FOR
PROCESS %d:\n",i);
for(j=1;j<=r;j++)
{
printf("\nFor Resource type %d :",j);
scanf("%d",&max[i][j]);
}}
printf("\nENTER THE ALLOCATED INSTANCES:\n");
for(i=1;i<=p;i++)
{
printf("\nPROCESS %d:",i);
printf("\n-------------");
for(j=1;j<=r;j++)
{
printf("\nResource Type - %d :",j);
scanf("%d",&m);
if(m<=avail[j])
{
alloc[i][j]=m;
avail[j]=avail[j]-m;
}
else
printf("\nALLOCATION EXCEEDS MAXIMUM. U CAN'T ALLOCATE IT.");
}
}
}
void disp1()
{
printf("\nNEEDED RESOURCES:");
printf("\n-----------------");
30
for(i=1;i<=p;i++)
{
printf("\nProcess %d:\t",i);
for(j=1;j<=r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
printf(" %d",need[i][j]);
}
}//for i
} //function
void seqnc()
{
top=1;
while(top<=p)
{
for(i=1;i<=p;i++)
{
buf=0;
z=0;
for(j=1;j<=r;j++)
{ z=z+need[i][j];
if(need[i][j]<=avail[j])
buf++;
}
if(buf==r&&z!=0)
{
a[top]=i;
top++;
for(k=1;k<=r;k++)
{
avail[k]=avail[k]+alloc[i][k];
need[i][k]=0;
}//for
} //if(buf==r)
} //for i
31
}//while
}//function
void disp2()
{
printf("\nThe Sequence of allocation to the processes:");
for(i=1;i<=p;i++)
printf(" %d",a[i]);
}
void main()
{
clrscr();
get();
disp1();
seqnc();
disp2();
getch();
}
Sample Input and Output:
ENTER THE NUMBER OF PROCESSES: 3
ENTER THE NUMBER OF RESOURCE TYPES: 2
ENTER THE NUMBER OF RESOURCES FOR TYPE 1 : 3
ENTER THE NUMBER OF RESOURCES FOR TYPE 2 : 2
ENTER THE MAXIMUM NUMBER OF RESOURCES REQUIRED FOR PROCESS 1:
For Resource type 1 : 2
For Resource type 2 : 1
ENTER THE MAXIMUM NUMBER OF RESOURCES REQUIRED FOR PROCESS 2:
For Resource type 1 : 1
For Resource type 2 : 1
ENTER THE MAXIMUM NUMBER OF RESOURCES REQUIRED FOR PROCESS 3:
For Resource type 1 : 3
For Resource type 2 : 2
ENTER THE ALLOCATED INSTANCES:
PROCESS 1:
------------Resource Type - 1 : 1
32
Resource Type - 2 : 1
PROCESS 2:
------------Resource Type - 1 : 1
Resource Type - 2 : 0
PROCESS 3:
------------Resource Type - 1 : 1
Resource Type - 2 : 1
Sample Viva Questions:
1. What is the Banker's Algorithm?
2. What are the key components of the Banker's Algorithm?
3. What is the difference between the Max and Allocation matrices?
Augmented Questions:
1. Write an enhanced version of the Banker’s Algorithm that supports dynamic resource requests from
processes at runtime.
33
Implementation of Deadlock Detection Algorithm
Exp.no: 8
Date:
Aim:
To write a C program to implement Deadlock Detection algorithm
Algorithm:
1: Start the Program
2: Obtain the required data through char and in data types.
3: Enter the filename, index block.
4: Print the file name index loop.
5: File is allocated to the unused index blocks
6: This is allocated to the unused linked allocation.
7: Stop the execution
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int found,flag,l,p[4][5],tp,tr,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
printf("Enter total no of processes");
scanf("%d",&tp);
printf("Enter total no of resources");
scanf("%d",&tr);
printf("Enter claim (Max. Need) matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&c[i][j]);
}
printf("Enter allocation matrix\n");
for(i=1;i<=tp;i++)
{
34
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&p[i][j]);
}
printf("Enter resource vector (Total resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&r[i]);
}
printf("Enter availability vector (available resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&a[i]);
47
temp[i]=a[i];
}
for(i=1;i<=tp;i++)
{ sum=0;
for(j=1;j<=tr;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=tp;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{ flag=1;
for(j=1;j<=tr;j++)
if(c[i][j]<temp[j])
35
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=tr;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{ found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
} if(found==0)
printf("%d\t",j);
}
getch();
}
Sample Input and Output:
Enter total no of processes: 4
Enter total no of resources: 3
Enter claim (Max. Need) matrix
process 1:
232
process 2:
322
process 3:
223
36
process 4:
112
Enter allocation matrix
process 1:
111
process 2:
101
process 3:
112
process 4:
011
Enter resource vector (Total resources):
10 10 10
Enter availability vector (available resources):
333
deadlock causing processes are:
3
4
Sample Viva Questions:
1. What is a Deadlock Detection Algorithm?
2. What is a Wait-for Graph?
3. What is the main difference between deadlock detection and deadlock avoidance?
Augmented Questions:
1. Display the wait-for graph, where edges are added or removed based on the state of resource requests and
releases.
2. Implement an advanced deadlock detection algorithm for systems with multiple instances (i.e., checking if
processes can eventually receive the resources they need)
3. Show a matrix of allocation, request, and available resources to track the state of the system.
37
Implementation of Threading
Exp.no: 9
Date:
Aim:
To Write C program to implement Threading
Algorithm:
1: Define a function func that takes a void* argument and returns a void* pointer.
2: Inside the func function, detach the current thread using pthread_detach(pthread_self()) so that it can
continue running independently of the parent thread.
3: Print a message indicating that the function is running.
4: Exit the thread using pthread_exit(NULL) so that it terminates.
5: Define a function fun.
6: Declare a pthread_t variable named ptid to store the ID of the new thread that will be created.
7: Inside the fun function, create a new thread using pthread_create(&ptid, NULL, &func, NULL) with the
func function as the thread function.
8: Print a message indicating that the current line may be printed before the thread terminates.
9: Compare the ID of the current thread with the ID of the newly created thread using pthread_equal(ptid,
pthread_self()).
10: If the IDs are equal, print a message indicating that the threads are equal.
11: If the IDs are not equal, print a message indicating that the threads are not equal.
12: Wait for the newly created thread to terminate using pthread_join(ptid, NULL).
13: Print a message indicating that the current line will be printed after the thread ends.
14: Exit the thread using pthread_exit(NULL).
Program:
// C program to show thread functions
#include <pthread.h> #include <stdio.h> #include <stdlib.h>
void* func(void* arg)
{
// from the calling thread pthread_detach(pthread_self());
printf("Inside the thread\n");
// exit the current thread pthread_exit(NULL);
}
void fun()
{
38
pthread_t ptid;
// Creating a new thread pthread_create(&ptid, NULL, &func, NULL); printf("This line may be printed"
" before thread terminates\n");
// The following line terminates
// the thread manually
// pthread_cancel(ptid);
// Compare the two threads created if(pthread_equal(ptid, pthread_self())
printf("Threads are equal\n");
else
printf("Threads are not equal\n");
// Waiting for the created thread to terminate pthread_join(ptid, NULL);
printf("This line will be printed" " after thread ends\n");
pthread_exit(NULL);
}
// Driver code int main()
{
fun(); return 0;
}
Sample Input and Output:
This line may be printed before thread terminates
Threads are not equal
Inside the thread
This line will be printed after the thread ends
Sample Viva Questions:
1. What is the concept of a thread pool?
2. What is a thread lifecycle?
3. What is thread synchronization? Why is it important?
Augmented Questions:
1. Show live updates on the condition of each thread (whether it's waiting, notifying, or running)
2. Display a queue of tasks, and show how threads in the pool pick up and complete tasks. Highlight when
tasks are queued or completed.
3. Show a real-time Gantt chart or timeline to visualize how threads are scheduled and how CPU time is
allocated to each thread under different scheduling policies.
39
Implementation of Paging Technique
Exp.no: 10
Date:
Aim:
To Implement the paging Technique using C program
Algorithm:
1: Declare variables to store the memory size, page size, number of pages, frame numbers for each page,
frame number, offset, logical address, physical address, loop counter, and choice.
2: Prompt the user to enter the memory size and print the value.
3: Prompt the user to enter the page size and store the value.
4: Calculate the number of pages by dividing the memory size by the page size and store the value.
5: Use a loop to prompt the user to enter the frame number for each page and store the values in an array.
6: Use a do-while loop to allow the user to enter a logical address and map it to a physical address until the
user chooses to stop.
7: Inside the do-while loop, prompt the user to enter a logical address and store the value.
8: Calculate the frame number by dividing the logical address by the page size and store the value.
9: Calculate the offset by finding the remainder of the logical address divided by the page size and store
the value.
10: Calculate the physical address by multiplying the frame number with the page size and adding the
offset, and store the value.
11: Print the physical address.
12: Prompt the user to continue or stop and store the choice.
13: Continue the loop if the choice is 1.
14: Exit the loop if the choice is 0.
15: Exit the program
Program:
#include <stdio.h>
int main()
{
int memsize = 15;
int pagesize, nofpage;
int p[100];
int frameno, offset;
int logadd, phyadd;
40
int i;
int choice = 0;
printf("Memory size is %d\n", memsize);
// Input page size
printf("Enter page size: ");
scanf("%d", &pagesize);
// Validate page size
if (pagesize <= 0 || pagesize > memsize)
{
printf("Invalid page size! Must be between 1 and %d.\n", memsize);
return 1;
}
// Calculate the number of pages
nofpage = memsize / pagesize;
printf("Number of pages: %d\n", nofpage);
// Input frame numbers for each page
for (i = 0; i < nofpage; i++)
{
printf("Enter the frame number for page %d: ", i);
scanf("%d", &p[i]);
// Validate frame number
if (p[i] < 0)
{
printf("Invalid frame number! Must be non-negative.\n");
return 1;
}
}
// Logical to physical address translation loop
do
{
printf("Enter a logical address: ");
scanf("%d", &logadd);
// Validate logical address
if (logadd < 0 || logadd >= memsize)
{
41
printf("Invalid logical address! Must be between 0 and %d.\n", memsize - 1);
continue;
}
frameno = logadd / pagesize;
offset = logadd % pagesize;
phyadd = (p[frameno] * pagesize) + offset;
printf("Physical address is: %d\n", phyadd);
printf("Do you want to continue (1 for Yes, 0 for No)?: ");
scanf("%d", &choice);
} while (choice == 1);
return 0;
}
Sample Input and Output:
Memory size is 15
Enter page size: 4
Number of pages: 3
Enter the frame number for page 0: 2
Enter the frame number for page 1: 1
Enter the frame number for page 2: 3
Enter a logical address: 5
Physical address is: 9
Do you want to continue (1 for Yes, 0 for No)?: 1
Enter a logical address: 12
Physical address is: 36
Do you want to continue (1 for Yes, 0 for No)?: 0
Sample Viva questions:
1. What is paging in an operating system?
2. What is the difference between logical address and physical address?
3. What is a page fault?
Augmented Questions:
1. Create a scenario where a process accesses several virtual pages that are initially not loaded into physical
memory.
2. Display a page table, showing how virtual pages are mapped to physical frames. The table should update in
real time as pages are mapped.
3. Create a simulation where users can define the size of virtual memory, page size, and physical memory.
42
Implementation of Memory Allocation Methods
Exp.no: 11
Date:
Aim:
To Write C programs to implement the following Memory Allocation Methods
a. First Fit
b. Worst Fit
c. Best Fit
a. First Fit Algorithm:
1: Initialize the memory and memory status arrays to indicate that all memory blocks are free.
2: Search for the first contiguous block of free memory that is large enough to hold the requested size.
3: If a block of sufficient size is found, allocate the block by setting the status of each memory location in
the block to "allocated" and return a pointer to the beginning of the block.
4: If a block of sufficient size is not found, return NULL to indicate that the allocation failed.
b.Worst fit Algorithm:
1: Initialize the memory and memory status arrays to indicate that all memory blocks are free.
2: Search for the largest contiguous block of free memory that is large enough to hold the requested size.
3: If a block of sufficient size is found, allocate the block by setting the status of each memory location in
the block to "allocated" and return a pointer to the beginning of the block.
4: If a block of sufficient size is not found, return NULL to indicate that the allocation failed.
c. Best fit Algorithm:
1: Initialize the memory and memory status arrays to indicate that all memory blocks are free.
2: Search for the smallest contiguous block of free memory that is large enough to hold the reuested size.
3: If a block of sufficient size is found, allocate the block by setting the status of each memory location in
the block to "allocated" and return a pointer to the beginning of the block.
4: If a block of sufficient size is not found, return NULL to indicate that the allocation failed.
Program:
#include <stdio.h>
#define MAX 100
void firstFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
for (int i = 0; i < n; i++)
allocation[i] = -1;
for (int i = 0; i < n; i++)
43
{
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i]) {
allocation[i] = j;
blockSize[j] -= processSize[i];
break;
}
}
}
printf("\nFirst Fit Allocation:\n");
printf("Process No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}
void bestFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
for (int i = 0; i < n; i++)
allocation[i] = -1;
for (int i = 0; i < n; i++)
{
int bestIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx])
bestIdx = j;
44
}
}
if (bestIdx != -1) {
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
}
}
printf("\nBest Fit Allocation:\n");
printf("Process No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}
void worstFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
for (int i = 0; i < n; i++)
allocation[i] = -1;
for (int i = 0; i < n; i++)
{
int worstIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (worstIdx == -1 || blockSize[j] > blockSize[worstIdx])
worstIdx = j;
}}
if (worstIdx != -1)
{
45
allocation[i] = worstIdx;
blockSize[worstIdx] -= processSize[i];
}
}
printf("\nWorst Fit Allocation:\n");
printf("Process No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}
int main()
{
int m, n;
int blockSize[MAX], processSize[MAX];
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
printf("Enter the size of each block: ");
for (int i = 0; i < m; i++)
scanf("%d", &blockSize[i]);
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the size of each process: ");
for (int i = 0; i < n; i++)
scanf("%d", &processSize[i]);
int blockSizeCopy[MAX];
// Run First Fit
for (int i = 0; i < m; i++)
blockSizeCopy[i] = blockSize[i];
firstFit(blockSizeCopy, m, processSize, n);
// Run Best Fit
46
for (int i = 0; i < m; i++)
blockSizeCopy[i] = blockSize[i];
bestFit(blockSizeCopy, m, processSize, n);
// Run Worst Fit
for (int i = 0; i < m; i++)
blockSizeCopy[i] = blockSize[i];
worstFit(blockSizeCopy, m, processSize, n);
return 0;
}
Sample Input and Output:
Enter the number of memory blocks: 5
Enter the size of each block: 100 500 200 300 600
Enter the number of processes: 4
Enter the size of each process: 212 417 112 426
First Fit Allocation:
Process No. Process Size Block No.
1
212
2
2
417
5
3
112
2
4
426
Not Allocated
Best Fit Allocation:
Process No. Process Size Block No.
1
212
4
2
417
5
3
112
1
4
426
Not Allocated
Worst Fit Allocation:
Process No. Process Size Block No.
1
212
5
2
417
2
3
112
5
4
426
Not Allocated
Sample Viva Questions:
1. What is contiguous memory allocation?
2. What is internal fragmentation?
47
3. What is a frame in paging?
Augmented Questions
1. Simulate dynamic memory allocation where processes are assigned partitions that fit their exact size.
2. Show how the TLB (Translation Lookaside Buffer) speeds up address translation.
3. Simulate a system where memory is divided into segments (e.g., code, data, stack). Users can allocate
different-sized segments to processes.
48
Implementation of Various Page Replacement Algorithms
Exp.no: 12
Date:
Aim:
To Write C programs to implement the various Page Replacement Algorithms using First-In, FirstOut (FIFO) , LRU (Least Recently used) and LFU (Least Frequently Used) Page Replacement Algorithm.
a. FIFO ALGORITHM:
1 :Initialize an empty queue (or array) of size equal to the number of frames.
2 :For each page request in the reference string:
If the page is already in the frames, do nothing (page hit).
If the page is not in the frames:
If there is space, insert the page into the frames.
If the frames are full, remove the oldest page (first-in) and insert the new page.
Increment the page fault counter.
3: At the end, print the total number of page faults.
b. LRU ALGORITHM:
1:Initialize an empty list (or array) of size equal to the number of frames.
2:For each page request:
If the page is already in the frames:
Move it to the most recently used position (update its access time).
If the page is not in the frames:
If there is space, insert the page.
If the frames are full, find the least recently used page (LRU) (smallest access time) and replace it.
Increment the page fault counter.
3:At the end, print the total number of page faults.
LFU ALGORITHM
1:Initialize an empty frame list and a frequency table.
2:For each page request:
If the page is already in the frames, increase its frequency count.
If the page is not in the frames:
If there is space, insert the page with frequency = 1.
If the frames are full, remove the page with the lowest frequency count.
49
Insert the new page and set its frequency to 1.
Increment the page fault counter.
3: At the end, print the total number of page faults.
PROGRAM:
#include <stdio.h>
#define MAX_FRAMES 10
#define MAX_REFERENCES 100
int frames[MAX_FRAMES]; // Page frames
int freq[MAX_FRAMES];
// Frequency array for LFU
int time[MAX_FRAMES];
// Time array for LRU
int pageFaults = 0, frameCount, referenceCount;
// Initialize frames to -1 (empty)
void initFrames()
{
for (int i = 0; i < frameCount; i++)
{
frames[i] = -1;
freq[i] = 0;
time[i] = 0;
}
pageFaults = 0;
}
// Check if a page exists in the frames, return its index or -1
int findPage(int page)
{
for (int i = 0; i < frameCount; i++)
{
if (frames[i] == page)
{
return i;
}
}
return -1;}
// Display current state of frames
50
void displayFrames()
{
for (int i = 0; i < frameCount; i++)
{
if (frames[i] == -1)
printf("- ");
else
printf("%d ", frames[i]);
}
printf("\n");
}
// FIFO Page Replacement Algorithm
void fifo(int references[]
{
int head = 0; // FIFO replacement pointer
initFrames();
for (int i = 0; i < referenceCount; i++)
{
int page = references[i];
if (findPage(page) == -1) { // Page fault
frames[head] = page;
head = (head + 1) % frameCount;
pageFaults++;
}
displayFrames();
}
printf("Total Page Faults using FIFO: %d\n", pageFaults);
}
// LRU Page Replacement Algorithm
void lru(int references[])
{
initFrames();
for (int i = 0; i < referenceCount; i++)
{
51
int page = references[i];
int index = findPage(page);
if (index != -1)
{
time[index] = i; // Update time of last use
}
else
{
// Find the Least Recently Used (smallest time)
int lruIndex = 0;
for (int j = 1; j < frameCount; j++)
{
if (time[j] < time[lruIndex])
{
lruIndex = j;
}
}
frames[lruIndex] = page;
time[lruIndex] = i; // Update time of use
pageFaults++;
}
displayFrames();
}
printf("Total Page Faults using LRU: %d\n", pageFaults);
}
// LFU Page Replacement Algorithm
void lfu(int references[])
{
initFrames();
for (int i = 0; i < referenceCount; i++)
{
int page = references[i];
int index = findPage(page);
if (index != -1)
52
{
freq[index]++; // Increase frequency
}
else
{
// Find the Least Frequently Used (smallest freq)
int lfuIndex = 0;
for (int j = 1; j < frameCount; j++)
{
if (freq[j] < freq[lfuIndex])
{
lfuIndex = j;
}
}
frames[lfuIndex] = page;
freq[lfuIndex] = 1; // Reset frequency for the new page
pageFaults++;
}
displayFrames();
}
printf("Total Page Faults using LFU: %d\n", pageFaults);
}
// Main function
int main()
{
int references[MAX_REFERENCES], choice;
// User input for page reference string
printf("Enter number of page references: ");
scanf("%d", &referenceCount);
printf("Enter the page reference string: ");
for (int i = 0; i < referenceCount; i++)
{
scanf("%d", &references[i]);
}
53
// User input for number of frames
printf("Enter number of frames: ");
scanf("%d", &frameCount);
// Menu for algorithm selection
printf("\nChoose Page Replacement Algorithm:\n");
printf("1. FIFO\n2. LRU\n3. LFU\nEnter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nExecuting FIFO Page Replacement...\n");
fifo(references);
break;
case 2:
printf("\nExecuting LRU Page Replacement...\n");
lru(references);
break;
case 3:
printf("\nExecuting LFU Page Replacement...\n");
lfu(references);
break;
default:
printf("Invalid choice! Please enter 1, 2, or 3.\n");
}
return 0;
}
Sample Input and Output:
Enter number of page references: 12
Enter the page reference string: 1 3 0 3 5 6 3 5 7 3 0 1
Enter number of frames: 3
Choose Page Replacement Algorithm:
1. FIFO
2. LRU
3. LFU
Enter your choice: 2
54
Executing LRU Page Replacement...
1-13130
130
530
560
563
563
763
763
063
061
Total Page Faults using LRU: 10
Sample Viva Questions:
1. What is Belady's Anomaly?
2. What is the Optimal (OPT) page replacement algorithm?
3. What is the difference between LRU and LFU in terms of page replacement?
Augmented Questions:
1. Display how the page fault rate changes as the number of frames increases or decreases.
2. Show real-time charts and graphs comparing the page fault count for each algorithm after each page
access.
3. Show a circular representation of the page frames, with a "clock hand" pointing to the current page being
considered for replacement.
55
Implementation of various File Organization Techniques
Exp.no: 13
Date:
Aim:
To Write C programs to Implement the various File Organization Techniques.
a. Single Level Algorithm:
1:Start
2:Initialize fileCount = 0
3:Create File:
If fileCount == MAX_FILES, print "Directory is full!" and return.
Read filename.
Store filename in singleLevel[fileCount].
Increment fileCount.
Print "File created successfully."
4:Display Files:
If fileCount == 0, print "No files in directory." and return.
Print all filenames in singleLevel[].
5: End
b. Two Level Algorithm:
1;Start
2:Initialize:
userCount = 0
userFileCount[i] = 0 for each user
3:Create User Directory:
If userCount == MAX_USERS, print "Maximum users reached!" and return.
Read username and store it in users[userCount].
Increment userCount.
Print "User directory created successfully."
4:Create File in a User Directory:
Read username.
Find userIndex where users[i] == username.
If not found, print "User not found!" and return.
If userFileCount[userIndex] == MAX_FILES, print "User's directory is full!" and return.
56
Read filename and store in twoLevel[userIndex][userFileCount[userIndex]].
Increment userFileCount[userIndex].
Print "File created successfully."
5:Display Files in Two-Level Directory:
If userCount == 0, print "No user directories available." and return.
For each user, print username and corresponding files[].
6:End
Program:
#include <stdio.h>
#include <string.h>
#define MAX_FILES 10
#define MAX_USERS 5
// Single-Level Directory
char singleLevel[MAX_FILES][20];
int fileCount = 0;
// Two-Level Directory
char users[MAX_USERS][20];
char twoLevel[MAX_USERS][MAX_FILES][20];
int userFileCount[MAX_USERS] = {0};
int userCount = 0;
// Function to create a file in Single-Level Directory
void createSingleLevelFile()
{
if (fileCount >= MAX_FILES)
{
printf("Directory is full!\n");
return;
}
printf("Enter filename: ");
scanf("%s", singleLevel[fileCount]);
fileCount++;
printf("File created successfully.\n");
}
// Function to display files in Single-Level Directory
57
void displaySingleLevelFiles()
{
if (fileCount == 0)
{
printf("No files in directory.\n");
return;
}
printf("Files in Single-Level Directory:\n");
for (int i = 0; i < fileCount; i++)
{
printf("%s\n", singleLevel[i]);
}
}
// Function to create a user directory in Two-Level Directory
void createUser()
{
if (userCount >= MAX_USERS)
{
printf("Maximum users reached!\n");
return;
}
printf("Enter username: ");
scanf("%s", users[userCount]);
userCount++;
printf("User directory created successfully.\n");
}
// Function to create a file in Two-Level Directory
void createTwoLevelFile()
{
char username[20], filename[20];
printf("Enter username: ");
scanf("%s", username);
int userIndex = -1;
for (int i = 0; i < userCount; i++)
{
58
if (strcmp(users[i], username) == 0)
{
userIndex = i;
break;
}
}
if (userIndex == -1)
{
printf("User not found!\n");
return;
}
if (userFileCount[userIndex] >= MAX_FILES)
{
printf("User's directory is full!\n");
return;
}
printf("Enter filename: ");
scanf("%s", twoLevel[userIndex][userFileCount[userIndex]]);
userFileCount[userIndex]++;
printf("File created successfully.\n");
}
// Function to display files in Two-Level Directory
void displayTwoLevelFiles()
{
if (userCount == 0)
{
printf("No user directories available.\n");
return;
}
for (int i = 0; i < userCount; i++)
{
printf("User: %s\n", users[i]);
if (userFileCount[i] == 0)
{
printf(" No files.\n");
59
}
else
{
for (int j = 0; j < userFileCount[i]; j++)
{
printf(" %s\n", twoLevel[i][j]);
}
}
}
}
// Main function to handle user input
int main()
{
int choice;
while (1)
{
printf("\nFile Organization Techniques:\n");
printf("1. Create File (Single-Level)\n");
printf("2. Display Files (Single-Level)\n");
printf("3. Create User (Two-Level)\n");
printf("4. Create File (Two-Level)\n");
printf("5. Display User Files (Two-Level)\n");
printf("6. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
createSingleLevelFile();
break;
case 2:
displaySingleLevelFiles();
break;
case 3:
createUser();
60
break;
case 4:
createTwoLevelFile();
break;
case 5:
displayTwoLevelFiles();
break;
case 6:
printf("Exiting program...\n");
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Sample Input and Output:
1
Enter filename: file1.txt
1
Enter filename: file2.txt
2
Files in Single-Level Directory:
file1.txt
file2.txt
3
Enter username: user1
4
Enter username: user1
Enter filename: fileA.txt
5
User: user1
fileA.txt
6
Exiting program...
61
Sample Viva Questions:
1. What is the difference between a file and a record in file organization?
2. What are the different access methods for file organization?
3. What is a "file allocation table" (FAT)?
Augmented Questions:
1. Create multiple files or data sets with related records (e.g., customer and order records).
2. Create a dataset with 5000 records, each containing multiple fields (e.g., ID, Name, Address, Date of
Birth).
3. Create a file with records and store them in non-contiguous blocks, simulating file fragmentation.
62
Implementation of File Allocation Strategies
Exp.no: 14
Date:
Aim:
To Implement the following File Allocation Strategies using C programs
a. Sequential
b. Indexed
c. Linked
a. Sequential Algorithm:
1:Start
2:Input the startBlock and size of the file.
3:Check if size number of contiguous blocks are free.
4:If free space is available:
Allocate the file from startBlock to startBlock + size - 1.
Mark blocks as allocated.
Print "File allocated successfully".
5:Else, print "Not enough contiguous free space!".
6: End
b.Indexed Algorithm:
1; Start
2:Input the indexBlock (block to store file index).
3:Check if indexBlock is free:
If not, print "Index block already allocated!" and stop.
4:Input blockCount (number of blocks required).
5:Find free blocks in memory.
6:If enough free blocks are found:
Allocate them and store block numbers in indexBlock.
Print "File allocated with index block and blocks list".
7:Else, print "Not enough free blocks!".
8;End
c.Linked Algorithm:
1: Start
2: Input startBlock (starting block of the file).
3: Check if startBlock is free:
If not, print "Start block already allocated!" and stop.
4: Input blockCount (number of blocks needed).
63
5: Find blockCount free blocks in memory.
6:If enough free blocks are found:
Allocate them.
Store pointers linking each block to the next.
Print "File allocated with linked blocks".
7:Else, print "Not enough free blocks!".
8:End
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX_BLOCKS 50
int memory[MAX_BLOCKS] = {0}; // 0 means free, 1 means allocated
// Structure for Indexed and Linked Allocation
typedef struct
{
int indexBlock;
int blocks[MAX_BLOCKS];
int blockCount;
} IndexedFile;
typedef struct
{
int startBlock;
int blocks[MAX_BLOCKS];
int blockCount;
} LinkedFile;
// Sequential Allocation
void sequentialAllocation(int start, int size)
{
int i, freeCount = 0;
// Check if sufficient space is available
for (i = start; i < start + size; i++)
{
if (memory[i] == 0) freeCount++;
}
64
if (freeCount == size)
{
for (i = start; i < start + size; i++)
memory[i] = 1;
printf("File allocated from block %d to %d.\n", start, start + size - 1);
}
else
{
printf("Not enough contiguous free space available!\n");
}
}
// Indexed Allocation
void indexedAllocation(IndexedFile *file) {
printf("Enter index block: ");
scanf("%d", &file->indexBlock);
if (memory[file->indexBlock] == 1) {
printf("Index block already allocated!\n");
return;
}
printf("Enter number of blocks: ");
scanf("%d", &file->blockCount);
int count = 0;
for (int i = 0; i < MAX_BLOCKS && count < file->blockCount; i++) {
if (memory[i] == 0) {
file->blocks[count++] = i;
memory[i] = 1;
}
}
if (count < file->blockCount) {
printf("Not enough free blocks available!\n");
} else {
memory[file->indexBlock] = 1;
printf("File allocated with index block %d. Blocks: ", file->indexBlock);
65
for (int i = 0; i < file->blockCount; i++) printf("%d ", file->blocks[i]);
printf("\n");
}
}
// Linked Allocation
void linkedAllocation(LinkedFile *file) {
printf("Enter start block: ");
scanf("%d", &file->startBlock);
if (memory[file->startBlock] == 1) {
printf("Start block already allocated!\n");
return;
}
printf("Enter number of blocks: ");
scanf("%d", &file->blockCount);
int count = 0;
for (int i = 0; i < MAX_BLOCKS && count < file->blockCount; i++) {
if (memory[i] == 0) {
file->blocks[count++] = i;
memory[i] = 1;
}
}
if (count < file->blockCount)
{
printf("Not enough free blocks available!\n");
}
else
{
memory[file->startBlock] = 1;
printf("File allocated starting from block %d. Blocks linked: ", file->startBlock);
for (int i = 0; i < file->blockCount; i++) printf("%d -> ", file->blocks[i]);
printf("NULL\n");
}
}
66
int main()
{
int choice, start, size;
IndexedFile indexedFile;
LinkedFile linkedFile;
while (1)
{
printf("\nFile Allocation Strategies:\n");
printf("1. Sequential Allocation\n");
printf("2. Indexed Allocation\n");
printf("3. Linked Allocation\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter start block and size: ");
scanf("%d %d", &start, &size);
sequentialAllocation(start, size);
break;
case 2:
indexedAllocation(&indexedFile);
break;
case 3:
linkedAllocation(&linkedFile);
break;
case 4:
printf("Exiting program...\n");
return 0;
default:
printf("Invalid choice! Please try again.\n");
} }
return 0;
}
67
Sample Input and Ouput:
File Allocation Strategies:
1. Sequential Allocation
2. Indexed Allocation
3. Linked Allocation
4. Exit
Enter choice: 1
Enter start block and size: 10 5
File allocated from block 10 to 14.
Enter choice: 2
Enter index block: 20
Enter number of blocks: 3
File allocated with index block 20. Blocks: 21 22 23
Enter choice: 3
Enter start block: 30
Enter number of blocks: 4
File allocated starting from block 30. Blocks linked: 31 -> 32 -> 33 -> 34 -> NULL
Enter choice: 4
Exiting program...
Sample Viva Questions:
1. What is a file allocation strategy?
2. What is the difference between a single-level index and a multi-level index?
3. What is the role of a file allocation table (FAT)?
Augmented Questions:
1. Create a virtual disk with a certain number of blocks (e.g., 100 blocks).
2. Implement linked allocation where each block contains a pointer to the next block in the file.
3. Create files of random sizes (e.g., 5, 10, 15, and 20 blocks) and allocate them non-contiguously.
68
Implementation of various Disk Scheduling Algorithms
Exp.no: 15
Date:
Aim:
To write a C program for the implementation of various disk scheduling algorithms
Algorithm:
a. FCFS (First-Come, First-Served):
1.
Requests are processed in the order they arrive.
2.
Calculate total seek time by summing up the absolute differences between successive request
positions.
b. SCAN (Elevator Algorithm):
1.
The disk arm moves in one direction, fulfilling requests in that direction, then reverses direction and
processes requests in the opposite direction.
c. C-SCAN (Circular SCAN):
1.
The disk arm moves in one direction, processes requests, and when it reaches the end, it jumps back
to the beginning without servicing any request, then continues servicing.
d. LOOK:
1.
Similar to SCAN, but the disk arm only goes as far as the last request in each direction before
reversing direction.
e. C-LOOK:
1.
Similar to C-SCAN, but the disk arm doesn't go to the extreme ends of the disk; it jumps directly to
the nearest request after completing a direction.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX_REQUESTS 50
// Function to calculate the total seek time in FCFS
void fcfs(int requests[], int n, int head)
{
int seekTime = 0;
printf("\nFCFS Disk Scheduling:\n");
for (int i = 0; i < n; i++)
{
seekTime += abs(requests[i] - head);
69
head = requests[i];
}
printf("Total seek time: %d\n", seekTime);
}
// Function to calculate the total seek time in SCAN
void scan(int requests[], int n, int head, int diskSize)
{
int seekTime = 0;
int left[MAX_REQUESTS], right[MAX_REQUESTS];
int leftIndex = 0, rightIndex = 0;
// Divide requests into left and right of the head
for (int i = 0; i < n; i++)
{
if (requests[i] < head)
{
left[leftIndex++] = requests[i];
} else {
right[rightIndex++] = requests[i];
}
}
// Sort both left and right requests
for (int i = 0; i < leftIndex - 1; i++)
{
for (int j = i + 1; j < leftIndex; j++)
{
if (left[i] < left[j])
{
int temp = left[i];
left[i] = left[j];
left[j] = temp;
}
}
}
for (int i = 0; i < rightIndex - 1; i++)
{
70
for (int j = i + 1; j < rightIndex; j++) {
if (right[i] > right[j]) {
int temp = right[i];
right[i] = right[j];
right[j] = temp;
}
}
}
// Move to the left end and then to the right end
seekTime += head; // Move to the leftmost request
seekTime += left[0];
for (int i = 0; i < leftIndex; i++) {
seekTime += abs(left[i] - left[i + 1]);
}
seekTime += abs(left[leftIndex - 1] - right[0]); // Move from left end to right end
for (int i = 0; i < rightIndex; i++) {
seekTime += abs(right[i] - right[i + 1]);
}
printf("\nSCAN Disk Scheduling:\n");
printf("Total seek time: %d\n", seekTime);
}
// Function to calculate the total seek time in C-SCAN
void cscan(int requests[], int n, int head, int diskSize) {
int seekTime = 0;
int left[MAX_REQUESTS], right[MAX_REQUESTS];
int leftIndex = 0, rightIndex = 0;
// Divide requests into left and right of the head
for (int i = 0; i < n; i++) {
if (requests[i] < head) {
left[leftIndex++] = requests[i];
} else {
right[rightIndex++] = requests[i];
}
}
// Sort both left and right requests
71
for (int i = 0; i < leftIndex - 1; i++)
{
for (int j = i + 1; j < leftIndex; j++)
{
if (left[i] < left[j])
{
int temp = left[i];
left[i] = left[j];
left[j] = temp;
}
}
}
for (int i = 0; i < rightIndex - 1; i++)
{
for (int j = i + 1; j < rightIndex; j++)
{
if (right[i] > right[j])
{
int temp = right[i];
right[i] = right[j];
right[j] = temp;
}
}
}
// Move to the rightmost end, then go to leftmost end and start moving to the right
seekTime += (diskSize - 1) - head;
seekTime += (diskSize - 1);
seekTime += right[0];
for (int i = 0; i < rightIndex; i++)
{
seekTime += abs(right[i] - right[i + 1]);
}
printf("\nC-SCAN Disk Scheduling:\n");
printf("Total seek time: %d\n", seekTime);
72
}
// Function to calculate the total seek time in LOOK
void look(int requests[], int n, int head)
{
int seekTime = 0;
int left[MAX_REQUESTS], right[MAX_REQUESTS];
int leftIndex = 0, rightIndex = 0;
// Divide requests into left and right of the head
for (int i = 0; i < n; i++)
{
if (requests[i] < head)
{
left[leftIndex++] = requests[i];
}
else
{
right[rightIndex++] = requests[i];
}
}
for (int i = 0; i < leftIndex - 1; i++)
{
for (int j = i + 1; j < leftIndex; j++)
{
if (left[i] < left[j])
{
int temp = left[i];
left[i] = left[j];
left[j] = temp;
}
}
}
for (int i = 0; i < rightIndex - 1; i++)
{
for (int j = i + 1; j < rightIndex; j++)
{
73
if (right[i] > right[j])
{
int temp = right[i];
right[i] = right[j];
right[j] = temp;
}
}
}
// Move towards the left, then move towards the right
seekTime += abs(head - left[0]);
for (int i = 0; i < leftIndex; i++)
{
seekTime += abs(left[i] - left[i + 1]);
}
seekTime += abs(left[leftIndex - 1] - right[0]);
for (int i = 0; i < rightIndex; i++)
{
seekTime += abs(right[i] - right[i + 1]);
}
printf("\nLOOK Disk Scheduling:\n");
printf("Total seek time: %d\n", seekTime);
}
// Function to calculate the total seek time in C-LOOK
void clook(int requests[], int n, int head)
{
int seekTime = 0;
int left[MAX_REQUESTS], right[MAX_REQUESTS];
int leftIndex = 0, rightIndex = 0;
// Divide requests into left and right of the head
for (int i = 0; i < n; i++)
{
if (requests[i] < head)
{
left[leftIndex++] = requests[i];
}
74
else
{
right[rightIndex++] = requests[i];
}
}
// Sort both left and right requests
for (int i = 0; i < leftIndex - 1; i++)
{
for (int j = i + 1; j < leftIndex; j++)
{
if (left[i] < left[j])
{
int temp = left[i];
left[i] = left[j];
left[j] = temp;
}
}
}
for (int i = 0; i < rightIndex - 1; i++)
{
for (int j = i + 1; j < rightIndex; j++)
{
if (right[i] > right[j])
{
int temp = right[i];
right[i] = right[j];
right[j] = temp;
}
}
}
for (int i = 0; i < rightIndex; i++)
{
seekTime += abs(right[i] - right[i + 1]);
75
}
seekTime += abs(right[rightIndex - 1] - left[0]);
for (int i = 0; i < leftIndex; i++)
{
seekTime += abs(left[i] - left[i + 1]);
}
printf("\nC-LOOK Disk Scheduling:\n");
printf("Total seek time: %d\n", seekTime);
}
// Main function
int main()
{
int requests[] = {176, 79, 34, 60, 92, 11, 41, 114};
int n = sizeof(requests) / sizeof(requests[0]);
int head = 50;
int diskSize = 200;
fcfs(requests, n, head);
scan(requests, n, head, diskSize);
cscan(requests, n, head, diskSize);
look(requests, n, head);
clook(requests, n, head);
return 0;
}
Sample Input and Output :
FCFS Disk Scheduling:
Total seek time: 573
SCAN Disk Scheduling:
Total seek time: 573
C-SCAN Disk Scheduling:
Total seek time: 590
LOOK Disk Scheduling:
Total seek time: 573
C-LOOK Disk Scheduling:
Total seek time: 573
76
Sample Viva Questions:
1. What are the main disk scheduling algorithms?
2. What is the SCAN (Elevator) disk scheduling algorithm?
3. What is the LOOK disk scheduling algorithm?
Augmented Questions:
1. Design and implement a new disk scheduling algorithm that optimizes seek time based on the following
criteria:
The algorithm should prioritize shortest seek time first (SSTF) but must avoid starvation of distant
requests.
Implement a priority-based scheduling mechanism where requests closer to the current head position get
higher priority, but distant requests are serviced periodically to ensure fairness.
Include a deadline mechanism, where if a request has been waiting too long, it gets elevated in priority
regardless of its position.
77
Installation of guest operating system Ubuntu using VMware
Exp.no: 16
Date:
Aim:
To install guest operating system Ubuntu using VMware
Procedure:
1: Install VMware Workstation/Player
Download VMware Workstation/Player
Visit the official VMware website: VMware Workstation Player (Free for personal use).
Download and install the appropriate version of VMware Workstation Player (or VMware
Workstation Pro if you prefer).
Follow the on-screen installation instructions to install VMware on your host system.
2: Download Ubuntu ISO
Go to the official Ubuntu download page: Ubuntu Downloads.
Select the version you want to install (e.g., Ubuntu 22.04 LTS), and download the ISO file. This
file is used to install Ubuntu inside the virtual machine.
3: Create a New Virtual Machine in VMware
Open VMware Workstation/Player
Launch the VMware Workstation or VMware Workstation Player application.
Create a New Virtual Machine
Click on "Create a New Virtual Machine" or "New Virtual Machine".
Choose "Typical" installation (recommended for beginners) and click Next.
Select the Installation Media
Choose "Installer disc image file (ISO)" and browse to the location where the Ubuntu ISO file
was downloaded.
Click Next.
Choose Guest Operating System
Select Linux for the Guest Operating System.
Choose Ubuntu (64-bit) as the version and click Next.
Name the Virtual Machine
Enter a name for your virtual machine (e.g., "Ubuntu VM").
Select a location to store the virtual machine files (by default, VMware stores them in your
"Documents" folder).
78
Click Next.
Allocate Virtual Machine Resources
RAM: Allocate at least 2 GB of RAM for Ubuntu. If you have more resources, allocate 4 GB or
more for better performance.
CPU: Allocate at least 1 CPU core (preferably 2 cores if your machine allows it). Click Next.
Set Disk Size
Allocate 20 GB or more for the virtual disk (the default size is typically sufficient).
Choose "Store virtual disk as a single file" for better performance.
Click Next.
Finish Setup
Review your configuration and click Finish.
4: Install Ubuntu on the Virtual Machine
Start the Virtual Machine
After creating the VM, click "Power on this virtual machine".
The VM will boot from the Ubuntu ISO file you selected earlier.
Install Ubuntu
Once the VM boots up, you will see the Ubuntu installation screen.
Select "Install Ubuntu" and press Enter.
Language Selection
Choose your desired language for the Ubuntu installation and click Continue.
Keyboard Layout
Choose your keyboard layout and click Continue.
Install Updates and Third-Party Software
Select "Download updates while installing Ubuntu" (recommended for up-to-date software).
Choose "Install third-party software" if you need support for multimedia codecs and hardware
(optional but recommended).
Click Continue.
Disk Partitioning
Select "Erase disk and install Ubuntu" to allow Ubuntu to automatically set up partitions on the
virtual disk.
Confirm by clicking Install Now.
Timezone and User Information
Select your timezone (you can search for your city).
Enter your name, computer name, username, and password.
Click Continue.
79
Installation
The installation process will begin and may take 10-20 minutes depending on the system and
internet connection.
When the installation completes, click Restart Now.
4: Complete Ubuntu Setup
Login to Ubuntu
After restarting, log in using the username and password you set during installation.
********************************************************************************
80
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )