0% found this document useful (0 votes)
40 views62 pages

Os Lab New-1

Uploaded by

darshangowda0525
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)
40 views62 pages

Os Lab New-1

Uploaded by

darshangowda0525
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/ 62

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

Belagavi-590018

Laboratory Manual
On
OPERATING SYSTEM
[BCS303]

Prepared By
Mrs. Soumya K N
Assistant Professor
Department of
AIML

Department of Artificial Intelligence and Machine Learning


Jyothy Institute of Technology
Tataguni, off kanakapura Road, bangalore-560082
Page 1
Academic Year 2023-24

Page 2
SL No. Experiment
1. Develop a c program to implement the Process system calls (fork (), exec(), wait(),
create process, terminate process)

2. Simulate the following CPU scheduling algorithms to find turnaround time and
waiting time a) FCFS b) SJF c) Round Robin d) Priority.

3. Develop a C program to simulate producer-consumer problem using semaphores

4. Develop a C program which demonstrates interprocess communication between a


reader process and a writer process. Use mkfifo, open, read, write and close APIs in
your program

5. Develop a C program to simulate Bankers Algorithm for DeadLock Avoidanc

6. Develop a C program to simulate the following contiguous memory allocation


Techniques: a) Worst fit b) Best fit c) First fit.

7. Develop a C program to simulate page replacement algorithms: a) FIFO b) LRU

8. Simulate following File Organization Techniques a) Single level directory b) Two


level directory

9. Develop a C program to simulate the Linked file allocation strategies

10. Develop a C program to simulate SCAN disk scheduling algorithm

Course outcomes (Course Skill Set):


At the end of the course, the student will be able to:

CO 1. Explain the structure and functionality of operating system

CO 2. Apply appropriate CPU scheduling algorithms for the given problem.

CO 3. Analyse the various techniques for process synchronization and deadlock handling.

CO 4. Apply the various techniques for memory management

CO 5. Explain file and secondary storage management strategies. CO 6. Describe the need for
Page 3
information protection mechanism

Page 4
Experiment No 1 Creation and Termination of Processes

Experiment Detail: Develop a c program to implement the Process system calls (fork (), exec(), wait(),
create process, terminate process)

Aim: Program to implement process system calls

Learning Objectives: Understand the basics of process creation and process termination.
Course Outcome:
CO 1. Explain the structure and functionality of operating system

Theory:
• The interface between a process and an operating system is provided by system calls.
• In general, system calls are available as assembly language instructions.
• They are also included in the manuals used by the assembly level programmers.
• System calls are usually made when a process in user mode requires access to a resource.
• Then it requests the kernel to provide the resource via a system call.
➢ fork( ): The fork system call creates a new process.
➢ exec( ): The exec( ) function replaces the current process image with a new process image specified by
path.
➢ Wait( ): A call to wait() blocks the calling process until one of its child processes exits or a signal is
received.

Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t child_pid;
int status;
// Create a child process
child_pid = fork();

if (child_pid < 0) {

Page 5
// Fork failed
perror("Fork failed");
exit(1);

Page 6
}
else if (child_pid == 0) {
// Child process
printf("Child process (PID: %d) is running.\n", getpid());

// Replace the child process with a new program


execlp("/bin/ls", "ls", "-l", NULL);

// If exec fails, the code below will be executed


perror("Exec failed");
exit(1);
}
else {
// Parent process
printf("Parent process (PID: %d) created a child (PID: %d).\n", getpid(), child_pid);

// Wait for the child process to finish


wait(&status);

if (WIFEXITED(status)) {
printf("Child process (PID: %d) exited with status %d.\n", child_pid, WEXITSTATUS(status));
}
else {
printf("Child process (PID: %d) did not exit normally.\n", child_pid);
}
}
return 0;
}

Output:
Parent process (PID: 999) created a child (PID: 1000).
Child process (PID: 1000) is running.
total 0
Child process (PID: 1000) exited with status 0.

Page 7
Experiment No 2a CPU Scheduling Algorithms-FCFS

Experiment Detail: Simulate the following CPU scheduling algorithms to find turnaround time and waiting
time a) FCFS b) SJF c) Round Robin d) Priority.

Learning Objectives: Understand the working of operating system in scheduling various processes in order
to utilize the CPU as a resource for the execution.

Course outcome:
CO2: Apply appropriate CPU scheduling algorithms for the given problem.

Theory:
• Scheduling of processes/work is done to finish the work on time.
• CPU Scheduling is a process that allows one process to use the CPU while another process is delayed (in
standby) due to unavailability of any resources such as I / O etc, thus making full use of the CPU.
• The purpose of CPU Scheduling is to make the system more efficient, faster, and fairer.
• Whenever the CPU becomes idle, the operating system must select one of the processes in the line ready for
execution.
• The selection process is done by a temporary (CPU) scheduler.
• The Scheduler selects between many processes which are ready to execute and assigns the CPU to one of them.

Aim: Program to simulate various CPU scheduling algorithms to calculate the turnaround time and waiting
time.

Algorithm:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer, totwtime and totttime is equal to zero.
Step 3: Get the value of ‘n’ assign pid as I and get the value of p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop calculate wait time and
turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by total number of process.
Step 6: Print total wait time and total turnaround time.
Step 7: Stop the program.

Program:
Page 8
#include <stdio.h>
struct Process {

int pid;

// Process ID

int arrival;

// Arrival time

int burst;

// Burst time
};

void fcfsScheduling(struct Process processes[], int n) {


int currentTime = 0;

printf("Process\tArrival Time\tBurst Time \tWaiting Time\tTurnaround Time\n");

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


if (currentTime < processes[i].arrival) {
currentTime = processes[i].arrival;
}

int waitingTime = currentTime - processes[i].arrival;


int turnaroundTime = waitingTime + processes[i].burst;
printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].arrival, processes[i].burst,
waitingTime, turnaroundTime);
currentTime += processes[i].burst;
}
}

int main() {
struct Process processes[] = {
{1, 0, 6},
{2, 2, 3},
{3, 3, 8}
};
int n = sizeof(processes) / sizeof(processes[0]);
fcfsScheduling(processes, n);
return 0;
}

Output:

Page 9
Process Arrival Time Burst Time Waiting Time Turnaround Time
1 0 6 0 6
2 2 3 4 7
3 3 8 6 14

Page 10
Experiment No 2b CPU Scheduling Algorithms-SJF

Aim: To write a C program to simulate SJF scheduling algorithm.

Algorithm:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer, totwtime and totttime is equal to zero.
Step 3: Get the value of ‘n’ assign pid as I and get the value of p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop calculate wait time and
turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by total number of process.
Step 6: Print total wait time and total turnaround time.
Step 7: Stop the program.

Program :
#include <stdio.h>
struct Process {
int pid; // Process ID
int burst; // Burst time
};

void findWaitingTime(struct Process proc[], int n, int wt[]) {


wt[0] = 0;
for (int i = 1; i < n; i++) {
wt[i] = proc[i - 1].burst + wt[i - 1];
}
}

void findTurnAroundTime(struct Process proc[], int n, int wt[], int tat[]) {


for (int i = 0; i < n; i++) {
tat[i] = proc[i].burst + wt[i];
}
}

void findAverageTime(struct Process proc[], int n) {


int wt[n], tat[n];
findWaitingTime(proc, n, wt);
findTurnAroundTime(proc, n, wt, tat);

float total_wt = 0, total_tat = 0;

printf("Process\tBurst Time\tWaiting Time\tTurnaround Time\n");


Page 11
for (int i = 0; i < n; i++) {

Page 12
total_wt += wt[i];
total_tat += tat[i];
printf("%d\t%d\t\t%d\t\t%d\n", proc[i].pid, proc[i].burst, wt[i], tat[i]);
}

printf("Average waiting time = %.2f\n", (float)total_wt / n);


printf("Average turnaround time = %.2f\n", (float)total_tat / n);
}

void sortProcesses(struct Process proc[], int n) {


// Implement a simple sorting algorithm (e.g., Bubble Sort) based on burst time
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (proc[j].burst > proc[j + 1].burst) {
struct Process temp = proc[j];
proc[j] = proc[j + 1];
proc[j + 1] = temp;
}
}
}
}

int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);

struct Process proc[n];

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


proc[i].pid = i + 1;
printf("Enter burst time for process %d: ", i + 1);
scanf("%d", &proc[i].burst);
}

sortProcesses(proc, n);

findAverageTime(proc, n);

return 0;
}

Output:
Enter the number of processes: 3
Page 13
Enter burst time for process 1: 6
Enter burst time for process 2: 3

Page 14
Enter burst time for process 3: 8

Process Burst Time Waiting Time Turnaround Time


2 3 0 3
1 6 3 9
3 8 9 17
Average waiting time = 4.00
Average turnaround time = 9.67

Page 15
Experiment No 2c CPU Scheduling Algorithms- Round Robin

Aim: To write a C program to simulate Round Robin scheduling algorithm.

Algorithm:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i, j as integer, totwtime and totttime is equal to zero.
Step 3: Get the value of ‘n’ assign pid as I and get the value of p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop calculate wait time and
turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by total number of process.
Step 6: Print total wait time and total turnaround time.
Step 7: Stop the program.

Program:
#include <stdio.h>
struct Process {
int pid; // Process ID
int burst; // Burst time
};

void roundRobinScheduling(struct Process processes[], int n, int timeQuantum) {


int remaining[n];
int currentTime = 0;

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


remaining[i] = processes[i].burst;
}

while (1) {
int allDone = 1; // Flag to check if all processes are completed

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


if (remaining[i] > 0) {
allDone = 0;
if (remaining[i] > timeQuantum) {
currentTime += timeQuantum;
remaining[i] -= timeQuantum;
printf("Process %d executed for time quantum %d\n remaining time %d\n", processes[i].pid,
timeQuantum, remaining[i]);
} else {
currentTime += remaining[i];
Page 16
remaining[i] = 0;
printf("Process %d executed for remaining time %d\n", processes[i].pid, remaining[i]);

Page 17
}
}
}
if (allDone)
break;
}
}

int main() {
struct Process processes[] = {
{1, 10},
{2, 5},
{3, 8},
{4, 12}
};
int n = sizeof(processes) / sizeof(processes[0]);
int timeQuantum = 4;
roundRobinScheduling(processes, n, timeQuantum);
return 0;
}

Output:
Process 1 executed for time quantum 4
remaining time 6
Process 2 executed for time quantum 4
remaining time 1
Process 3 executed for time quantum 4
remaining time 4
Process 4 executed for time quantum 4
remaining time 8
Process 1 executed for time quantum 4
remaining time 2
Process 2 executed for remaining time 0
Process 3 executed for remaining time 0
Process 4 executed for time quantum 4
remaining time 4
Process 1 executed for remaining time 0
Process 4 executed for remaining time 0

Page 18
Experiment No 2d CPU Scheduling Algorithms- Priority

Aim: To write a C program to simulate Priority scheduling algorithm.

Algorithm:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i, j as integer, totwtime and totttime is equal to zero.
Step 3: Get the value of ‘n’ assign pid as I and get the value of p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop calculate wait time and
turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by total number of process.
Step 6: Print total wait time and total turnaround time.
Step 7: Stop the program.

Program:
#include <stdio.h>
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int n;
printf("Enter Number of Processes: ");
scanf("%d",&n);

// b is array for burst time, p for priority and index for process id
int b[n],p[n],index[n];
for(int i=0;i<n;i++)
{
printf("Enter Burst Time and Priority Value for Process %d: ",i+1);
scanf("%d %d",&b[i],&p[i]);
index[i]=i+1;
}
for(int i=0;i<n;i++)
{
int a=p[i],m=i;

//Finding out highest priority element and placing it at its desired position
for(int j=i;j<n;j++)
{
Page 19
if(p[j] > a)
{
a=p[j];

Page 20
m=j;
}
}

//Swapping processes
swap(&p[i], &p[m]);
swap(&b[i], &b[m]);
swap(&index[i],&index[m]);
}

// T stores the starting time of process


int t=0;

//Printing scheduled process


printf("Order of process Execution is\n");
for(int i=0;i<n;i++)
{
printf("P%d is executed from %d to %d\n",index[i],t,t+b[i]);
t+=b[i];
}
printf("\n");
printf("Process Id Burst Time Wait Time TurnAround Time\n");
int wait_time=0;
for(int i=0;i<n;i++)
{
printf("P%d %d %d %d\n",index[i],b[i],wait_time,wait_time + b[i]);
wait_time += b[i];
}
return 0;
}

Output:
Enter Number of Processes: 3
Enter Burst Time and Priority Value for Process 1: 3 0
Enter Burst Time and Priority Value for Process 2: 6 2
Enter Burst Time and Priority Value for Process 3: 8 1
Order of process Execution is
P2 is executed from 0 to 6
P3 is executed from 6 to 14
P1 is executed from 14 to 17

Process Id Burst Time Wait Time TurnAround Time


P2 6 0 6
P3 8 6 14
Page 21
P1 3 14 17

Page 22
Experiment No 3 Producer Consumer Problem

Experiment Detail: Develop a C program to simulate producer-consumer problem using semaphores

Aim:To write a C-program to simulate the producer – consumer problem using semaphores.

Algorithm:
Step 1: Start the program.
Step 2: Declare the required variables.
Step 3: Initialize the buffer size and get maximum item you want to produce.
Step 4: Get the option, which you want to do either producer, consumer or exit from the
operation.
Step 5: If you select the producer, check the buffer size if it is full the producer should not
produce the item or otherwise produce the item and increase the value buffer size.
Step 6: If you select the consumer, check the buffer size if it is empty the consumer should not
consume the item or otherwise consume the item and decrease the value of buffer size.
Step 7: If you select exit come out of the program.
Step 8: Stop the program.

Program:
#include <stdio.h>
int mutex = 1, full = 0, empty = 3, x = 0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n");
while (1)
{
printf("\nENTER YOUR CHOICE\n");
scanf("%d", &n);
switch (n)
{
case 1:
if ((mutex == 1) && (empty != 0))
producer();
else
printf("BUFFER IS FULL");
break;
case 2:
Page 23
if ((mutex == 1) && (full != 0))
consumer();

Page 24
else
printf("BUFFER IS EMPTY");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return (++s);
}
void producer()
{
mutex = wait(mutex);
full = signal(full);
empty = wait(empty);
x++;
printf("\nproducer produces the item%d", x);
mutex = signal(mutex);
}
void consumer()
{
mutex = wait(mutex);
full = wait(full);
empty = signal(empty);
printf("\n consumer consumes item%d", x);
x--;
mutex = signal(mutex);
}
Output:

Page 25
Experiment No 4 Interprocess Communication

Experiment Detail: Develop a C program which demonstrates interprocess communication between a


reader process and a writer process. Use mkfifo, open, read, write and close APIs in your program

Program:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
mkfifo(myfifo, 0666);
char arr1[80], arr2[80];
while (1)
{
fd = open(myfifo, O_WRONLY);
fgets(arr2, 80, stdin);
write(fd, arr2, strlen(arr2)+1);
close(fd);
fd = open(myfifo, O_RDONLY);
read(fd, arr1, sizeof(arr1));
printf("%s\n", arr1);
close(fd);
}
return 0;
}

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{

int fd1;
char *myfifo = "/tmp/myfifo";
mkfifo(myfifo, 0666);
Page 26
char str1[80], str2[80];
while (1){
fd1 = open(myfifo,O_RDONLY);

Page 27
read(fd1, str1, 80);
printf("Client: %s\n", str1);
close(fd1);
strcpy(str2 , "Server Replied:");
strcat(str2,str1);
write(fd1, str2, strlen(str2)+1);
close(fd1);
}
return 0;
}

Procedure to Execute Program:


• Compile the writer and reader programs separately, and then run them in two different terminals.
• Make sure to compile with -lm to link the math library:
• gcc writer.c -o writer
• gcc reader.c -o reader
• Run the writer in one terminal:
• ./writer
• Run the reader in another terminal:
• ./reader
• The writer will create the named pipe (FIFO) and write a message to it, and the reader will open the same
named pipe, read the message, and display it.
• This demonstrates interprocess communication using named pipes.

Output:

Page 28
Experiment No 5 Bankers Algorithm For Deadlock Avoidance

Experiment Detail: Develop a C program to simulate Bankers Algorithm for DeadLock Avoidanc
Aim:
To write a C program to implement banker‟s algorithm for deadlock avoidance.

Algorithm:
Step 1: Start the program.
Step 2: Declare the memory for the process.
Step 3: Read the number of process, resources, allocation matrix and available matrix.
Step 4: Compare each and every process using the banker’s algorithm.
Step 5: If the process is in safe state then it is a not a deadlock process otherwise it is a
deadlock process
Step 6: produce the result of state of process
Step 7: Stop the program.

Program:
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;
n = 5;
m = 3;
int alloc[5][3] = {{0, 1, 0},
{2, 0, 0}, // P1
{3, 0, 2}, // P2
{2, 1, 1}, // P3
{0, 0, 2}}; // P4

int max[5][3] = {{7, 5, 3},


{3, 2, 2}, // P1
{9, 0, 2}, // P2
{2, 2, 2}, // P3
{4, 3, 3}}; // P4

int avail[3] = {3, 3, 2};


int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++)
{
f[k] = 0;
}
Page 29
int need[n][m];
for (i = 0; i < n; i++)

Page 30
{
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}

int y = 0;
for (k = 0; k < 5; k++){
for (i = 0; i < n; i++){
if (f[i] == 0)
{
int flag = 0;
for (j = 0; j < m; j++)
{
if (need[i][j] > avail[j])
{
flag = 1;
break;
}
}

if (flag == 0)
{
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for (int i = 0; i < n; i++)
{
if (f[i] == 0)
{
flag = 0;
printf("The following system is not safe");
break;
}
}
if (flag == 1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);

Page 31
printf(" P%d", ans[n - 1]);
}
return (0);

Page 32
}

Output:
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2

Page 33
Experiment No 6a Memory Allocation-Worst Fit

Experiment Detail: Develop a C program to simulate the following contiguous memory allocation
Techniques: a) Worst fit b) Best fit c) First fit.

Program:
#include <stdio.h>
// Define the maximum number of memory blocks
#define MAX_BLOCKS 100
// Structure to represent memory blocks
struct MemoryBlock {
int block_id;
int size;
int allocated;
};
// Function to perform worst-fit memory allocation
void worstFit(struct MemoryBlock blocks[], int m, int processSize) {
int worstIdx = -1;
for (int i = 0; i < m; i++) {
if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (worstIdx == -1 || blocks[i].size > blocks[worstIdx].size) {
worstIdx = i;
}
}
}
if (worstIdx != -1) {
// Allocate the memory block
blocks[worstIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, worstIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}

Page 34
}
int main() {

Page 35
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
struct MemoryBlock blocks[MAX_BLOCKS];
for (int i = 0; i < m; i++) {
blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}
int n; // Number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
worstFit(blocks, m, processSize);
}
return 0;
}

Output:
Enter the number of memory blocks: 5
Enter the size of memory block 1: 100
Enter the size of memory block 2: 500
Enter the size of memory block 3: 200
Enter the size of memory block 4: 300
Enter the size of memory block 5: 600
Enter the number of processes: 4
Enter the size of process 1: 212
Process with size 212 allocated to block 5
Enter the size of process 2: 417
Process with size 417 allocated to block 2
Enter the size of process 3: 112
Process with size 112 allocated to block 4
Enter the size of process 4: 426
Cannot allocate the process with size 426
Page 36
Experiment No 6b Memory Allocation-Best Fit

Program:
#include <stdio.h>
// Define the maximum number of memory blocks
#define MAX_BLOCKS 100
// Structure to represent memory blocks
struct MemoryBlock {
int block_id;
int size;
int allocated;
};

// Function to perform best-fit memory allocation


void bestFit(struct MemoryBlock blocks[], int m, int processSize) {
int bestIdx = -1;

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


if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (bestIdx == -1 || blocks[i].size < blocks[bestIdx].size) {
bestIdx = i;
}
}
}
if (bestIdx != -1) {
// Allocate the memory block
blocks[bestIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, bestIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}
}
int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
struct MemoryBlock blocks[MAX_BLOCKS];
for (int i = 0; i < m; i++) {
blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}
int n; // Number of processes
printf("Enter the number of processes: ");
Page 37
scanf("%d", &n);
for (int i = 0; i < n; i++) {

Page 38
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
bestFit(blocks, m, processSize);
}

return 0;
}
Output:
Enter the number of memory blocks: 5
Enter the size of memory block 1: 100
Enter the size of memory block 2: 500
Enter the size of memory block 3: 200
Enter the size of memory block 4: 300
Enter the size of memory block 5: 600
Enter the number of processes: 4
Enter the size of process 1: 212
Process with size 212 allocated to block 4
Enter the size of process 2: 417
Process with size 417 allocated to block 2
Enter the size of process 3: 112
Process with size 112 allocated to block 3
Enter the size of process 4: 426
Process with size 426 allocated to block 5

Page 39
Experiment No 6c Memory Allocation-First Fit

Program:
#include <stdio.h>
// Define the maximum number of memory blocks
#define MAX_BLOCKS 100
// Structure to represent memory blocks
struct MemoryBlock {
int block_id;
int size;
int allocated;
};

// Function to perform first-fit memory allocation


void firstFit(struct MemoryBlock blocks[], int m, int processSize) {
for (int i = 0; i < m; i++) {
if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
// Allocate the memory block
blocks[i].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, i + 1);
return;
}
}
printf("Cannot allocate the process with size %d\n", processSize);
}

int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);

struct MemoryBlock blocks[MAX_BLOCKS];

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


blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}
int n; // Number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);

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


int processSize;
Page 40
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);

Page 41
firstFit(blocks, m, processSize);
}
return 0;
}

Output:
Enter the number of memory blocks: 5
Enter the size of memory block 1: 100
Enter the size of memory block 2: 500
Enter the size of memory block 3: 200
Enter the size of memory block 4: 300
Enter the size of memory block 5: 600
Enter the number of processes: 4
Enter the size of process 1: 212
Process with size 212 allocated to block 2
Enter the size of process 2: 417
Process with size 417 allocated to block 5
Enter the size of process 3: 112
Process with size 112 allocated to block 3
Enter the size of process 4: 426
Cannot allocate the process with size 426

Page 42
Experiment No 7a Page Replacement Algorithm-FIFO

Experiment Detail: Develop a C program to simulate page replacement algorithms: a) FIFO b) LRU
Program:
#include <stdio.h>
int main()
{
int incomingStream[] = {4 , 1 , 2 , 4 , 5,4,1,2,3,6};
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)
Page 43
printf(" %d\t\t\t", temp[n]);
else

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

Output:
Incoming Frame 1 Frame 2 Frame 3
4 4 - -
1 4 1 -
2 4 1 2
4 4 1 2
5 5 1 2
4 5 4 2
1 5 4 1
2 2 4 1
3 2 3 1
6 2 3 6
Total Page Faults: 9

Page 45
Experiment No 7b Page Replacement Algorithm-LRU

Program:
#include<stdio.h>
#include<limits.h>

int checkHit(int incomingPage, int queue[], int occupied){

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


if(incomingPage == queue[i])
return 1;
}

return 0;
}

void printFrame(int queue[], int occupied)


{
for(int i = 0; i < occupied; i++)
printf("%d\t\t\t",queue[i]);
}

int main()
{

// int incomingStream[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1};


// int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2, 4, 3};
int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3};

int n = sizeof(incomingStream)/sizeof(incomingStream[0]);
int frames = 3;
int queue[n];
int distance[n];
int occupied = 0;
int pagefault = 0;

printf("Page\t Frame1 \t Frame2 \t Frame3\n");

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


{
printf("%d: \t\t",incomingStream[i]);
// what if currently in frame 7
// next item that appears also 7
// didnt write condition for HIT
Page 46
if(checkHit(incomingStream[i], queue, occupied)){

Page 47
printFrame(queue, occupied);
}

// filling when frame(s) is/are empty


else if(occupied < frames){
queue[occupied] = incomingStream[i];
pagefault++;
occupied++;

printFrame(queue, occupied);
}
else{

int max = INT_MIN;


int index;
// get LRU distance for each item in frame
for (int j = 0; j < frames; j++)
{
distance[j] = 0;
// traverse in reverse direction to find
// at what distance frame item occurred last
for(int k = i - 1; k >= 0; k--)
{
++distance[j];

if(queue[j] == incomingStream[k])
break;
}

// find frame item with max distance for LRU


// also notes the index of frame item in queue
// which appears furthest(max distance)
if(distance[j] > max){
max = distance[j];
index = j;
}
}
queue[index] = incomingStream[i];
printFrame(queue, occupied);
pagefault++;
}

printf("\n");
}

Page 48
printf("Page Fault: %d",pagefault);

return 0;

Page 49
}

Output:
Page Frame1 Frame2 Frame3
1: 1
2: 1 2
3: 1 2 3
2: 1 2 3
1: 1 2 3
5: 1 2 5
2: 1 2 5
1: 1 2 5
6: 1 2 6
2: 1 2 6
5: 5 2 6
6: 5 2 6
3: 5 3 6
1: 1 3 6
3: 1 3 6
Page Fault: 8

Page 50
Experiment No 8a File Organization Techniques- Single Level Directory

Experiment Detail: Simulate following File Organization Techniques a) Single level directory b) Two level
directory

Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Maximum number of files in the directory
#define MAX_FILES 100
// Maximum file name length
#define MAX_NAME_LENGTH 256
// File structure to represent files
typedef struct File {
char name[MAX_NAME_LENGTH];
int size;
char content[1024]; // For simplicity, we use a fixed content size
} File;

// Directory structure to hold files


typedef struct Directory {
File files[MAX_FILES];
int num_files;
} Directory;

// Function to create a new file


File createFile(const char* name, int size, const char* content) {
File newFile;
strncpy(newFile.name, name, MAX_NAME_LENGTH);
newFile.size = size;
strncpy(newFile.content, content, sizeof(newFile.content));
return newFile;
}

// Function to add a file to the directory


void addFileToDirectory(Directory* directory, File file) {
if (directory->num_files < MAX_FILES) {
directory->files[directory->num_files] = file;
directory->num_files++;
} else {
printf("Directory is full. Cannot add more files.\n");
}
}
Page 51
// Function to display the contents of the directory
void displayDirectoryContents(const Directory* directory) {

Page 52
printf("Directory Contents:\n");
for (int i = 0; i < directory->num_files; i++) {
printf("File: %s, Size: %d\n", directory->files[i].name, directory->files[i].size);
}
}

int main() {
Directory directory;
directory.num_files = 0;
// Create and add files to the directory
File file1 = createFile("File1.txt", 100, "This is the content of File1.");
addFileToDirectory(&directory, file1);
File file2 = createFile("File2.txt", 200, "Content of File2 goes here.");
addFileToDirectory(&directory, file2);
// Display the directory contents
displayDirectoryContents(&directory);
return 0;
}

Output:
Directory Contents:
File: File1.txt, Size: 100
File: File2.txt, Size: 200

Page 53
Experiment No 8b File Organization Techniques- Two Level Directory
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_DIRS 100


#define MAX_FILES 100

struct FileEntry {
char name[50];
char content[1000];
};

struct Directory {
char name[50];
struct FileEntry files[MAX_FILES];
int num_files;
};

int num_dirs = 0;
struct Directory directories[MAX_DIRS];

void createDirectory(char parent_name[], char dir_name[]) {


if (num_dirs >= MAX_DIRS) {
printf("Error: Maximum directories reached.\n");
return;
}

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


if (strcmp(directories[i].name, parent_name) == 0) {
if (directories[i].num_files >= MAX_FILES) {
printf("Error: Maximum files reached in %s.\n", parent_name);
return;
}

strcpy(directories[num_dirs].name, dir_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
num_dirs++;
printf("Directory %s created in %s.\n", dir_name, parent_name);
return;
}
}
Page 54
printf("Error: Parent directory not found.\n");

Page 55
}

void createFile(char dir_name[], char file_name[]) {


for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, dir_name) == 0) {
if (directories[i].num_files >= MAX_FILES) {
printf("Error: Maximum files reached in %s.\n", dir_name);
return;
}

strcpy(directories[i].files[directories[i].num_files].name, file_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
printf("File %s created in %s.\n", file_name, dir_name);
return;
}
}

printf("Error: Directory not found.\n");


}

void listFiles(char dir_name[]) {


for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, dir_name) == 0) {
printf("Files in directory %s:\n", dir_name);
for (int j = 0; j < directories[i].num_files; j++) {
printf("%s\n", directories[i].files[j].name);
}
return;
}
}
printf("Error: Directory not found.\n");
}

int main() {
strcpy(directories[0].name, "root");
directories[0].num_files = 0;
num_dirs++;
char parent[50], dir[50], file[50];
createDirectory("root", "docs");
createDirectory("root", "images");
createFile("docs", "document1.txt");
createFile("docs", "document2.txt");
createFile("images", "image1.jpg");
listFiles("docs");

Page 56
listFiles("images");
return 0;
}

Page 57
Output:
Directory docs created in root.
Directory images created in root.
File document1.txt created in docs.
File document2.txt created in docs.
File image1.jpg created in images.
Files in directory docs:
document1.txt
document2.txt
Files in directory images:
image1.jpg

Page 58
Experiment No 9 Linked File Allocation
Experiment Detail: Develop a C program to simulate the Linked file allocation strategies
#include <stdio.h>
#include <stdlib.h>
int main(){
int f[50], p, i, st, len, j, c, k, a;
for (i = 0; i < 50; i++)
f[i] = 0;
printf("Enter how many blocks already allocated: ");
scanf("%d", &p);
printf("Enter blocks already allocated: ");
for (i = 0; i < p; i++) {
scanf("%d", &a);
f[a] = 1;
}
x:
printf("Enter index starting block and length: ");
scanf("%d%d", &st, &len);
k = len;
if (f[st] == 0)
{
for (j = st; j < (st + k); j++){
if (f[j] == 0){
f[j] = 1;
printf("%d --- >", j);
}
else{
//printf("%d Block is already allocated \n", j);
k++;
}
}
}
else
printf("%d starting block is already allocated \n", st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if (c == 1)
goto x;
else
exit(0);
return 0;
}

Page 59
Experiment No 10 SCAN Disk Scheduling
Experiment Detail: Develop a C program to simulate SCAN disk scheduling algorithm
Program:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
int pos[] = {90,120,35,122,38,128,65,68};
for(i=1;i<=n;i++)
{
//scanf("%d",&temp);
temp = pos[i-1];
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
Page 60
}
}
for(i=0;i<temp2-1;i++)

Page 61
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]<queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];

//queue[i]=max;
//queue[i+1]=0;
for(i=temp1+1,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}

Output:

Page 62

You might also like