OS LAB Programs - Colab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

1.

PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING


keyboard_arrow_down SYSTEMS (OPENDIR, READDIR CLOSEDIR)

ALGORITHM:
STEP 1: Start the program.
STEP 2: Create struct dirent.
STEP 3: declare the variable buff and pointer dptr.
STEP 4: Get the directory name.
STEP 5: Open the directory.
STEP 6: Read the contents in directory and print it.
STEP 7: Close the directory.

%%writefile 1.c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main() {
char dirName[100];
struct dirent *entry;
DIR *dir;

printf("Enter directory name: ");


scanf("%s", dirName);

if ((dir = opendir(dirName)) == NULL) {


printf("Directory does not exist.\n");
return 1;
}

while ((entry = readdir(dir)) != NULL) {


printf("%s\n", entry->d_name);
}

closedir(dir);
return 0;
}

Writing 1.c

!gcc 1.c

!./a.out
Enter directory name: a
Directory does not exist.

2. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING


keyboard_arrow_down SYSTEM (fork, getpid, exit)

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.
STEP 4: If pid==-1, exit.
STEP 5: Ifpid!=-1 , get the process id using getpid().
STEP 6: Print the process id.
STEP 7: Stop the program

%%writefile 2.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
int pid = fork();

if (pid == -1) {
printf("Error in process creation\n");
return 1;
}

if (pid != 0) {
printf("Parent process ID: %d\n", getpid());
} else {
printf("Child process ID: %d\n", getpid());
}

return 0;
}

Writing 2.c

!gcc 2.c

!./a.out

Parent process ID: 597


Child process ID: 598
3. FIRST COME FIRST SERVE - CPU SCHEDULING
keyboard_arrow_down ALGORITHM

ALGORITHM:
Step 1 : Input Number of Processes
Step 2: Input the processes burst time (bt).
Step 3: Find waiting time (wt) for all processes.
● As first process that comes need not to wait so waiting time for process 1 will be 0, i
● Find waiting time for all other processes i.e. for process i ->wt[i] = bt[i-1] + wt[i-1
Step 4: Find turnaround time = waiting_time + burst_time for all processes.
Step 5: Find average waiting time = total_waiting_time / no_of_processes.
Step 6: Similarly, find average turnaround time = total_turn_around_time / no_of_processes.
%%writefile FCFS.c
#include <stdio.h>

int main() {
int pid[15], bt[15], wt[15], n;
float twt = 0, tat = 0;

printf("Enter the number of processes: ");


scanf("%d", &n);

printf("Enter process IDs and burst times (ID BT):\n");


for (int i = 0; i < n; i++) {
scanf("%d %d", &pid[i], &bt[i]);
}

wt[0] = 0; // First process has no waiting time

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


wt[i] = wt[i - 1] + bt[i - 1];
twt += wt[i]; // Add to total waiting time
}

printf("Process ID Burst Time Waiting Time TurnAround Time\n");


for (int i = 0; i < n; i++) {
int tat_i = wt[i] + bt[i]; // Turnaround time for each process
tat += tat_i; // Add to total turnaround time
printf("%d %d %d %d\n", pid[i], bt[i], wt[i], tat_i
}

printf("Average Waiting Time = %.2f\n", twt / n);


printf("Average Turnaround Time = %.2f\n", tat / n);

return 0;
}

Overwriting FCFS.c

!gcc FCFS.c

!./a.out

Enter the number of processes: 3


Enter process IDs and burst times (ID BT):
1 10
2 5
3 8
Process ID Burst Time Waiting Time TurnAround Time
1 10 0 10
2 5 10 15
3 8 15 23
Average Waiting Time = 8.33
Average Turnaround Time = 16.00
keyboard_arrow_down 4. SHORTEST JOB FIRST - CPU SCHEDULING
ALGORITHM

ALGORITHM:
Step 1: Enter number of processes.
Step 2: Enter the burst time of all the processes.
Step 3: Sort all the processes according to their burst time and its respective process numbe
Step 4: Find waiting time, WT of all the processes.
Step 5: For the smallest process, WT = 0.
Step 6: For all the next processes i, find waiting time by adding burst time of all the previ
Step 7: Calculate Turnaround time = WT + BT for all the processes.
Step 8: Calculate average waiting time = total waiting time / no. of processes.
Step 9: Calculate average turnaround time= total turnaround time / no. of processes.

%%writefile SJF.c
#include <stdio.h>

int main() {
int n, pid[15], bt[15], wt[15], tat[15];
float twt = 0, ttat = 0;

printf("Enter the number of processes: ");


scanf("%d", &n);

printf("Enter process IDs and burst times (ID BT):\n");


for (int i = 0; i < n; i++) {
scanf("%d %d", &pid[i], &bt[i]);
}

// Sort processes by burst time (SJF logic)


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (bt[j] > bt[j + 1]) {
// Swap burst times
int temp = bt[j];
bt[j] = bt[j + 1];
bt[j + 1] = temp;
// Swap process IDs
temp = pid[j];
pid[j] = pid[j + 1];
pid[j + 1] = temp;
}
}
}

wt[0] = 0; // First process has no waiting time

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


wt[i] = wt[i - 1] + bt[i - 1]; // Calculate waiting time
twt += wt[i]; // Add to total waiting time
}

printf("Process ID Burst Time Waiting Time TurnAround Time\n");


for (int i = 0; i < n; i++) {
tat[i] = wt[i] + bt[i]; // Turnaround time for each process
ttat += tat[i]; // Add to total turnaround time
printf("%d %d %d %d\n", pid[i], bt[i], wt[i], tat[i
}

printf("Average Waiting Time = %.2f\n", twt / n);


printf("Average Turnaround Time = %.2f\n", ttat / n);

return 0;
}

Writing SJF.c

!gcc SJF.c

!./a.out

Enter the number of processes: 4


Enter process IDs and burst times (ID BT):
1 6
2 8
3 7
4 3
Process ID Burst Time Waiting Time TurnAround Time
4 3 0 3
1 6 3 9
3 7 9 16
2 8 16 24
Average Waiting Time = 7.00
Average Turnaround Time = 13.00

5. SHORTEST REMAINING TIME FIRST (SRTF) - CPU


keyboard_arrow_down SCHEDULING ALGORITHM

ALGORITHM:
Step 1: Enter number of processes.
Step 2: Enter the burst time and arrival time of all the processes.
Step 3: Sort all the processes according to their arrival time and its respective process bur
Step 4 Traverse until all process gets completely executed.
● Find process with minimum remaining time at every single time lap.
● Reduce its time by 1.
● Check if its remaining time becomes 0
● Increment the counter of process completion.
● Completion time of current process = current_time + 1;
● Calculate waiting time for each completed process.
● wt[i]= Completion time – arrival_time-burst_time
● Increment time lap by one.
Step 5: Calculate Turnaround time = WT + BT for all the processes.
Step 6: Calculate average waiting time = total waiting time / no. of processes.
Step 7 Calculate average turnaround time= total turnaround time / no. of processes.

%%writefile SRTF.c
#include <stdio.h>

int main() {
int n, i, smallest, time, count = 0, end_time;
int at[10], bt[10], rt[10]; // Arrival Time, Burst Time, Remaining Time
int wt = 0, tat = 0, completed = 0;
float avg_wt, avg_tat;

printf("Enter the number of processes: ");


scanf("%d", &n);

printf("\nEnter Arrival Time and Burst Time for each process:\n");


for (i = 0; i < n; i++) {
printf("Process %d:\n", i + 1);
printf("Arrival Time & Burst Time for Process-%d: ", i+1);
scanf("%d %d", &at[i], &bt[i]);
rt[i] = bt[i]; // Initialize remaining time as burst time
}

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

// Variables for tracking


int total_wt = 0, total_tat = 0;

for (time = 0; completed < n; time++) {


smallest = -1;

// Find the process with the smallest remaining time that has arrived
for (i = 0; i < n; i++) {
if (at[i] <= time && rt[i] > 0) {
if (smallest == -1 || rt[i] < rt[smallest]) {
smallest = i;
}
}
}

if (smallest == -1) {
continue; // If no process is ready, skip the time unit
}

// Execute the selected process


rt[smallest]--;

// Check if the process is completed


if (rt[smallest] == 0) {
completed++;
end_time = time + 1; // Time at which the process completes
int turnaround_time = end_time - at[smallest];
int waiting_time = turnaround_time - bt[smallest];

total_tat += turnaround_time;
total_wt += waiting_time;

// Print details for the completed process


printf("P%d\t%d\t\t%d\t\t%d\t\t%d\n",
smallest + 1, at[smallest], bt[smallest], turnaround_time, waiting_time)
}
}

// Calculate averages
avg_wt = (float)total_wt / n;
avg_tat = (float)total_tat / n;

printf("\nAverage Turnaround Time = %.2f", avg_tat);


printf("\nAverage Waiting Time = %.2f\n", avg_wt);

return 0;
}

Overwriting SRTF.c

!gcc SRTF.c

!./a.out

Enter the number of processes: 4

Enter Arrival Time and Burst Time for each process:


Process 1:
Arrival Time & Burst Time for Process-1: 0 8
Process 2:
Arrival Time & Burst Time for Process-2: 1 4
Process 3:
Arrival Time & Burst Time for Process-3: 2 9
Process 4:
Arrival Time & Burst Time for Process-4: 3 5

Process Arrival Time Burst Time Turnaround Time Waiting Time


P2 1 4 4 0
P4 3 5 7 2
P1 0 8 17 9
P3 2 9 24 15

Average Turnaround Time = 13.00


Average Waiting Time = 6.50

keyboard_arrow_down 6. PRIORITY - CPU SCHEDULING ALGORITHM


ALGORITHM:
Step 1: Take input for number of process, Burst time and priority of each process.
Step 2: Sort the processes in ascending order based on priority of each process.
Step 3: Find the waiting time for each process
Step: 4: Calculate the turnaround time of each process.
Step 5: Calculate average waiting time and average turnaround time.

%%writefile Priority.c
#include <stdio.h>

int main() {
int bt[20], p[20], pri[20], wt[20], tat[20], i, j, n, total = 0, totalT = 0, pos, temp;
float avg_wt, avg_tat;

// Get the number of processes


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

// Get burst time and priority for each process


printf("\nEnter Burst Time and Priority:\n");
for (i = 0; i < n; i++) {
printf("Enter Burst Time for p%d: ", i + 1);
scanf("%d", &bt[i]);
printf("Enter Priority for p%d: ", i + 1);
scanf("%d", &pri[i]);
p[i] = i + 1; // Process ID
}

// Sorting processes based on priority (ascending order)


for (i = 0; i < n; i++) {
pos = i;
for (j = i + 1; j < n; j++) {
if (pri[j] < pri[pos]) {
pos = j; // Find process with higher priority (lower value)
}
}

// Swap priorities, burst times, and process IDs


temp = pri[i];
pri[i] = pri[pos];
pri[pos] = temp;

temp = bt[i];
bt[i] = bt[pos];
bt[pos] = temp;

temp = p[i];
p[i] = p[pos];
p[pos] = temp;
}

wt[0] = 0; // Waiting time for the first process is 0

// Calculate waiting time for each process


for (i = 1; i < n; i++) {
wt[i] = 0;
for (j = 0; j < i; j++) {
wt[i] += bt[j]; // Sum of burst times of all previous processes
}
total += wt[i]; // Total waiting time
}

// Calculate average waiting time


avg_wt = (float)total / n;

// Calculate turnaround time for each process and total turnaround time
printf("\nProcess\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i]; // Turnaround time = Burst Time + Waiting Time
totalT += tat[i]; // Total Turnaround Time
printf("p%d\t\t%d\t\t%d\t\t%d\t\t%d\n", p[i], bt[i], pri[i], wt[i], tat[i]);
}

// Calculate average turnaround time


avg_tat = (float)totalT / n;

// Print average waiting and turnaround times


printf("\nAverage Waiting Time = %.2f", avg_wt);
printf("\nAverage Turnaround Time = %.2f\n", avg_tat);

return 0;
}

Writing Priority.c

!gcc Priority.c

!./a.out

Enter number of processes: 4

Enter Burst Time and Priority:


Enter Burst Time for p1: 5
Enter Priority for p1: 3
Enter Burst Time for p2: 3
Enter Priority for p2: 1
Enter Burst Time for p3: 8
Enter Priority for p3: 2
Enter Burst Time for p4: 6
Enter Priority for p4: 4

Process Burst Time Priority Waiting Time Turnaround Time


p2 3 1 0 3
p3 8 2 3 11
p1 5 3 11 16
p4 6 4 16 22

Average Waiting Time = 7.50


Average Turnaround Time = 13.00
7. ROUND ROBIN SCHEDULING - CPU SCHEDULING
keyboard_arrow_down ALGORITHMS

ALGORITHM:
Step 1: Take input for number of process and Burst time of each process.
Step 2: Take input for time quantum
Step 3: Find the waiting time for each process
Step 4: Calculate the turnaround time of each process.
Step 5: Calculate average waiting time and average turnaround time.

%%writefile RR.c

#include <stdio.h>

int main() {
// Input number of processes
int n;
printf("Enter Total Number of Processes: ");
scanf("%d", &n);

// Declare necessary arrays and variables


int wait_time = 0, ta_time = 0;
int arr_time[n], burst_time[n], temp_burst_time[n];
int x = n; // Process count

// Input process details (arrival time and burst time)


for (int i = 0; i < n; i++) {
printf("Enter Details of Process %d:\n", i + 1);
printf("Arrival Time: ");
scanf("%d", &arr_time[i]);
printf("Burst Time: ");
scanf("%d", &burst_time[i]);
temp_burst_time[i] = burst_time[i]; // Save the burst time for processing
}

// Input time slot for round-robin scheduling


int time_slot;
printf("Enter Time Slot: ");
scanf("%d", &time_slot);

// Initialize counters
int total = 0, counter = 0, i = 0;
printf("\nProcess ID\tBurst Time\tTurnaround Time\tWaiting Time\n");

// Round Robin Scheduling


while (x != 0) {
// If the process can be completed within the time slot
if (temp_burst_time[i] <= time_slot && temp_burst_time[i] > 0) {
total += temp_burst_time[i];
temp_burst_time[i] = 0; // Process completed
counter = 1; // Mark process as completed
}
// If the process needs more time
else if (temp_burst_time[i] > 0) {
temp_burst_time[i] -= time_slot;
total += time_slot;
}

// When a process is completed


if (temp_burst_time[i] == 0 && counter == 1) {
x--; // Decrease process count
printf("P%d\t\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i],
total - arr_time[i], total - arr_time[i] - burst_time[i]);
// Calculate waiting and turnaround times
wait_time += total - arr_time[i] - burst_time[i];
ta_time += total - arr_time[i];
counter = 0; // Reset counter for the next process
}

// Move to the next process


if (i == n - 1) {
i = 0; // Reset to the first process
}
else if (arr_time[i + 1] <= total) {
i++;
}
else {
i = 0; // Reset if no process is ready
}
}

// Calculate and print the average waiting and turnaround times


float average_wait_time = wait_time * 1.0 / n;
float average_turnaround_time = ta_time * 1.0 / n;
printf("\nAverage Waiting Time: %.2f", average_wait_time);
printf("\nAverage Turnaround Time: %.2f\n", average_turnaround_time);

return 0;
}

Overwriting RR.c

!gcc RR.c

!./a.out

Enter Total Number of Processes: 3


Enter Details of Process 1:
Arrival Time: 1
Burst Time: 5
Enter Details of Process 2:
Arrival Time: 1
Burst Time: 3
Enter Details of Process 3:
Arrival Time: 1
Burst Time: 3
Enter Time Slot: 2

Process ID Burst Time Turnaround Time Waiting Time


P2 3 8 5
P3 3 9 6
P1 5 10 5

Average Waiting Time: 5.33


Average Turnaround Time: 9.00

8. PRODUCER CONSUMER PROBLEM USING


keyboard_arrow_down 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 opera
Step 5: If you select the producer, check the buffer size if it is full the producer should n
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
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.

%%writefile producer_consumer.c

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

int mutex = 1, full = 0, empty = 3, x = 0;


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\n", x);
mutex = signal(mutex);
}

void consumer() {
mutex = wait(mutex);
full = wait(full);
empty = signal(empty);
printf("\nConsumer consumes item %d\n", x);
x--;
mutex = signal(mutex);
}

int main() {
int n;

printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n");

while(1) {
printf("\nENTER YOUR CHOICE: ");
scanf("%d", &n);

switch(n) {
case 1:
if((mutex == 1) && (empty != 0))
producer();
else
printf("BUFFER IS FULL\n");
break;

case 2:
if((mutex == 1) && (full != 0))
consumer();
else
printf("BUFFER IS EMPTY\n");
break;

case 3: printf("Exiting the program.");


exit(0);
break;

default:
printf("Invalid choice. Please try again.\n");
break;
}
}
return 0;
}

Writing producer_consumer.c

!gcc producer_consumer.c

!./a.out
1.PRODUCER
2.CONSUMER
3.EXIT

ENTER YOUR CHOICE: 1

Producer produces the item 1

ENTER YOUR CHOICE: 1

Producer produces the item 2

ENTER YOUR CHOICE: 1

Producer produces the item 3

ENTER YOUR CHOICE: 1


BUFFER IS FULL

ENTER YOUR CHOICE: 1


BUFFER IS FULL

ENTER YOUR CHOICE: 2

Consumer consumes item 3

ENTER YOUR CHOICE: 2

Consumer consumes item 2

ENTER YOUR CHOICE: 2

Consumer consumes item 1

ENTER YOUR CHOICE: 2


BUFFER IS EMPTY

ENTER YOUR CHOICE: 3


Exiting the program.

Double-click (or enter) to edit

keyboard_arrow_down 9. IPC USING SHARED MEMORY


ALGORITHM:
Step 1: Start the process
Step 2: Declare the segment size
Step 3: Create the shared memory
Step 4: Read the data from the shared memory
Step 5: Write the data to the shared memory
Step 6: Edit the data
Step 7: Stop the process.

%%writefile IPC_sender.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/shm.h>
#include<string.h>
int main()
{
int i;
void *shared_memory;
char buff[100];
int shmid;
shmid=shmget((key_t)2345, 1024, 0666|IPC_CREAT); //creates shared memory segment with key 23
printf("Key of shared memory is %d\n",shmid);
shared_memory=shmat(shmid,NULL,0); //process attached to shared memory segment
printf("Process attached at %p\n",shared_memory); //this prints the address where the segmen
printf("Enter some data to write to shared memory\n");
read(0,buff,100); //get some input from user
strcpy(shared_memory,buff); //data written to shared memory
printf("You wrote : %s\n",(char *)shared_memory);
}

Writing IPC_sender.c

!gcc IPC_sender.c

!./a.out

Key of shared memory is 1


Process attached at 0x10ebc3a64000
Enter some data to write to shared memory
Namaskaram
You wrote : Namaskaram

%%writefile IPC_Reciever.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/shm.h>
#include<string.h>
int main()
{
int i;
void *shared_memory;
char buff[100];
int shmid;
shmid=shmget((key_t)2345, 1024, 0666);
printf("Key of shared memory is %d\n",shmid);
shared_memory=shmat(shmid,NULL,0); //process attached to shared memory segment
printf("Process attached at %p\n",shared_memory);
printf("Data read from shared memory is : %s\n",(char *)shared_memory);
}

Overwriting IPC_Reciever.c

!gcc IPC_Reciever.c

!./a.out

Key of shared memory is 1


Process attached at 0x13b534f91000
Data read from shared memory is : Namaskaram

keyboard_arrow_down 10. BANKERS 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

%%writefile bankers.c

#include <stdio.h>

int main() {
int p, c, count = 0, terminate = 0;
int alc[10][10], max[10][10], need[10][10], safe[10], available[10], done[10] = {0};

// Input number of processes and resources


printf("Enter the number of processes and resources: ");
scanf("%d %d", &p, &c);

// Input allocation matrix


printf("Enter the allocation of resources for all processes (%d x %d matrix):\n", p, c)
for (int i = 0; i < p; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &alc[i][j]);
}
}

// Input maximum matrix


printf("Enter the maximum resources required by each process (%d x %d matrix):\n", p, c
for (int i = 0; i < p; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &max[i][j]);
}
}

// Input available resources


printf("Enter the available resources (%d values):\n", c);
for (int i = 0; i < c; i++) {
scanf("%d", &available[i]);
}

// Calculate the need matrix


printf("\nNeed resources matrix:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < c; j++) {
need[i][j] = max[i][j] - alc[i][j];
if (need[i][j] < 0) {
printf("Error: Need cannot be negative.\n");
return -1;
}
printf("%d\t", need[i][j]);
}
printf("\n");
}

// Banker's Algorithm
while (count < p) {
int found = 0;
for (int i = 0; i < p; i++) {
if (!done[i]) {
int j;
for (j = 0; j < c; j++) {
if (need[i][j] > available[j]) {
break;
}
}

if (j == c) {
// Safe to execute process
safe[count++] = i;
for (int k = 0; k < c; k++) {
available[k] += alc[i][k];
}
done[i] = 1;
found = 1;
}
}
}

if (!found) {
printf("System is not in a safe state.\n");
return -1;
}
}
// Output results
printf("\nAvailable resources after completion:\n");
for (int i = 0; i < c; i++) {
printf("%d\t", available[i]);
}
printf("\n");

printf("Safe sequence is: ");


for (int i = 0; i < count; i++) {
printf("P%d ", safe[i]);
}
printf("\n");

return 0;
}

Writing bankers.c

!gcc bankers.c

!./a.out

Enter the number of processes and resources: 3 3


Enter the allocation of resources for all processes (3 x 3 matrix):
0 1 0
2 0 0
3 0 2
Enter the maximum resources required by each process (3 x 3 matrix):
7 5 3
3 2 2
9 0 2
Enter the available resources (3 values):
3 3 2

Need resources matrix:


7 4 3
1 2 2
6 0 0
System is not in a safe state.

11. FIRST FIT - MEMORY ALLOCATION METHODS FOR


keyboard_arrow_down FIXED PARTITION

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

%%writefile firstfit.c

#include<stdio.h>

void main() {
int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

// Initialize flags and allocation arrays


for (i = 0; i < 10; i++) {
flags[i] = 0; // 0 means not allocated
allocation[i] = -1; // -1 means no process allocated to this block
}

// Get the number of blocks and their sizes


printf("Enter number of blocks: ");
scanf("%d", &bno);
printf("\nEnter size of each block: ");
for (i = 0; i < bno; i++) {
scanf("%d", &bsize[i]);
}

// Get the number of processes and their sizes


printf("\nEnter number of processes: ");
scanf("%d", &pno);
printf("\nEnter size of each process: ");
for (i = 0; i < pno; i++) {
scanf("%d", &psize[i]);
}

// First-fit allocation algorithm


for (i = 0; i < pno; i++) { // Loop through each process
for (j = 0; j < bno; j++) { // Loop through each block
if (flags[j] == 0 && bsize[j] >= psize[i]) { // If block is free and large enoug
allocation[j] = i; // Allocate process to block
flags[j] = 1; // Mark the block as allocated
break; // Move to the next process
}
}
}

// Display the allocation details


printf("\nBlock no.\tsize\t\tprocess no.\t\tsize");
for (i = 0; i < bno; i++) {
printf("\n%d\t\t%d\t\t", i + 1, bsize[i]); // Block details
if (flags[i] == 1) { // If the block is allocated
printf("%d\t\t\t%d", allocation[i] + 1, psize[allocation[i]]);
} else { // If the block is not allocated
printf("Not allocated");
}
}
}

Writing firstfit.c
!gcc firstfit.c

!./a.out

Enter number of blocks: 4

Enter size of each block: 100 200 300 400

Enter number of processes: 3

Enter size of each process: 150 250 350

Block no. size process no. size


1 100 Not allocated
2 200 1 150
3 300 2 250
4 400 3 350

12. BEST FIT - MEMORY ALLOCATION METHODS FOR


keyboard_arrow_down FIXED PARTITION

ALGORITHM:
Step 1: Input memory blocks and processes with sizes.
Step 2: Initialize all memory blocks as free.
Step 3: Start by picking each process and find the minimum block size that can be assigned to
find min(bockSize[1], blockSize[2],. ... blockSize[n]) > processSize[current], if found then
Step 4: If not then leave that process and keep checking the further processes.

%%writefile BestFit.c
#include <stdio.h>

void main() {
int fragment[20], b[20], p[20], i, j, nb, np, temp, lowest = 9999;
static int barray[20], parray[20];

printf("\n\t\t\tMemory Management Scheme - Best Fit");

// Input number of blocks


printf("\nEnter the number of blocks: ");
scanf("%d", &nb);

// Input number of processes


printf("Enter the number of processes: ");
scanf("%d", &np);
// Input sizes of blocks
printf("\nEnter the size of the blocks:\n");
for (i = 1; i <= nb; i++) {
printf("Block no.%d: ", i);
scanf("%d", &b[i]);
}

// Input sizes of processes


printf("\nEnter the size of the processes:\n");
for (i = 1; i <= np; i++) {
printf("Process no.%d: ", i);
scanf("%d", &p[i]);
}

// Best Fit Allocation


for (i = 1; i <= np; i++) {
lowest = 9999; // Reset the lowest for each process
parray[i] = 0; // Initialize no block allocated

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


if (barray[j] == 0) { // Block not yet allocated
temp = b[j] - p[i]; // Calculate fragment (remaining space)
if (temp >= 0 && temp < lowest) { // Find the best fitting block
parray[i] = j; // Assign the block to the process
lowest = temp; // Update the lowest fragment
}
}
}

if (parray[i] != 0) { // If a block was allocated


fragment[i] = lowest; // Store the fragment size
barray[parray[i]] = 1; // Mark block as allocated
} else {
fragment[i] = -1; // No suitable block found
}
}

// Display the results


printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");
for (i = 1; i <= np; i++) {
printf("\n%d\t\t%d\t\t", i, p[i]);
if (parray[i] != 0) {
printf("%d\t\t%d\t\t%d", parray[i], b[parray[i]], fragment[i]);
} else {
printf("Not Allocated");
}
}
}

Overwriting BestFit.c

!gcc BestFit.c

!./a.out
Memory Management Scheme - Best Fit
Enter the number of blocks: 3
Enter the number of processes: 3

Enter the size of the blocks:


Block no.1: 100
Block no.2: 500
Block no.3: 200

Enter the size of the processes:


Process no.1: 212
Process no.2: 412
Process no.3: 112

Process_no Process_size Block_no Block_size Fragment


1 212 2 500 288
2 412 Not Allocated
3 112 3 200 88
!./a.out

You might also like