Os Exp 1-10 Print

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

PROCESS SYSTEM CALLS

Exp. No.: 1(a) Date:


SOURCE CODE:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


int pid;
pid = fork();
if (pid < 0) {
printf("fork failed");
exit(1);
} else if (pid == 0) {
execlp("whoami", "ls", NULL);
exit(0);
} else {
printf("\nProcess id is - %d \n", getpid());
exit(0);
}
}

OUTPUT:
Process id is - 15272
I/O SYSTEM CALLS
Exp. No.: 1(b) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
char buffer[100];
int fd = open("input.txt", O_RDONLY); // open the file for reading
if (fd == -1)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}

int nbytes = read(fd, buffer, sizeof(buffer)); // read from the file into
buffer
if (nbytes == -1)
{
perror("Error reading file");
exit(EXIT_FAILURE);
}

close(fd); // close the file

printf("Read %d bytes from file: %s\n", nbytes, buffer);

fd = open("output.txt", O_WRONLY | O_CREAT/*, S_IRUSR | S_IWUSR*/); // open


the file for writing
if (fd == -1)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}

int nwritten = write(fd, buffer, nbytes); // write the contents of buffer to


the file
if (nwritten == -1)
{
perror("Error writing file");
exit(EXIT_FAILURE);
}

close(fd); // close the file

printf("Wrote %d bytes to file\n", nwritten);

return 0;
}
OUTPUT:
Read 20 bytes from file: hello from aanand!!!
Wrote 20 bytes to file
NAMED PIPE -WRITE
Exp. No.: 2-I Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO_FILE "myfifo"

int main()
{
int fd;
char data[100];
fd = open(FIFO_FILE, O_WRONLY);
printf("Enter data to be written to the pipe: ");
fgets(data, sizeof(data), stdin);
write(fd, data, sizeof(data));
close(fd);
return 0;
}

OUTPUT:
Enter data to be written to the pipe: Good Morning from NamedPipe.
NAMED PIPE - READ
Exp. No.: 2-II Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO_FILE "myfifo"
int main()
{
int fd;
char data[100];
fd = open(FIFO_FILE, O_RDONLY);
read(fd, data, sizeof(data));
printf("Received data: %s", data);
close(fd);
return 0;
}

OUTPUT:
Received data: Good Morning from NamedPipe.
UNNAMED PIPE
Exp. No.: 2-III Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
int fd[2];
pid_t pid;
char data[100];

if (pipe(fd) == -1)
{
perror("pipe");
exit(1);
}

pid = fork();
if (pid == -1)
{
perror("fork");
exit(1);
}

if (pid == 0)
{
close(fd[1]);
read(fd[0], data, sizeof(data));
printf("Child process received data from parent process: %s", data);
close(fd[0]);
}
else
{
close(fd[0]);
printf("Enter data to be sent to the child process: ");
fgets(data, sizeof(data), stdin);
write(fd[1], data, sizeof(data));
close(fd[1]);
}

return 0;
}

OUTPUT:
Enter data to be sent to the child process: hello from aanand!
Child process received data from parent process: hello from aanand!
FILE PERMISSIONS
Exp. No.: 3 Date:
SOURCE CODE:
#include <sys/stat.h>
#include <stdio.h>

int main() {
int ret;
char *filename = "myfile.txt";
mode_t mode = S_IRUSR | S_IWUSR /*| S_IRGRP | S_IWGRP | S_IROTH */; // Set
file permissions to 664

ret = chmod(filename, mode);

if (ret == 0) {
printf("File permissions for %s have been set to %o.\n", filename, mode);
} else {
printf("Error setting file permissions for %s.\n", filename);
}

return 0;
}

OUTPUT:
File permissions for myfile.txt have been set to 600.
FCFS (FIRST IN, FIRST OUT) CPU SCHEDULING
Exp. No.: 4(a) Date:
SOURCE CODE:
#include<stdio.h>

int main() {
int n, burst_time[20], waiting_time[20], turnaround_time[20], i;
float avg_waiting_time = 0, avg_turnaround_time = 0;

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


scanf("%d", &n);

printf("\nEnter burst time for each process:\n");


for(i = 0; i < n; i++) {
printf("Process[%d]: ", i+1);
scanf("%d", &burst_time[i]);
}

// Calculating waiting time for each process


waiting_time[0] = 0; // First process has a waiting time of 0
for(i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i-1] + burst_time[i-1];
}

// Calculating turnaround time for each process


for(i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
}

// Calculating average waiting time and turnaround time


for(i = 0; i < n; i++) {
avg_waiting_time += waiting_time[i];
avg_turnaround_time += turnaround_time[i];
}
avg_waiting_time /= n;
avg_turnaround_time /= n;

// Displaying results
printf("\nProcess\t Burst Time\t Waiting Time\t Turnaround Time\n");
for(i = 0; i < n; i++) {
printf("P[%d]\t %d\t\t %d\t\t %d\n", i+1, burst_time[i], waiting_time[i],
turnaround_time[i]);
}
printf("Average Waiting Time: %f\n", avg_waiting_time);
printf("Average Turnaround Time: %f\n", avg_turnaround_time);

return 0;
}
OUTPUT:
Enter the number of processes: 5

Enter burst time for each process:


Process[1]: 3
Process[2]: 24
Process[3]: 10
Process[4]: 11
Process[5]: 7

Process Burst Time Waiting Time Turnaround Time


P[1] 3 0 3
P[2] 24 3 27
P[3] 10 27 37
P[4] 11 37 48
P[5] 7 48 55
Average Waiting Time: 23.000000
Average Turnaround Time: 34.000000
SJF (SHORT JOB FIRST) CPU SCHEDULING
Exp. No.: 4(b) Date:
SOURCE CODE:
#include <stdio.h>
#include <limits.h>

int main() {
int n, i, j, burst_time[20], remaining_time[20], waiting_time[20],
turnaround_time[20], process[20], smallest, current_time = 0, completed = 0;
float avg_waiting_time = 0, avg_turnaround_time = 0, total_waiting_time = 0,
total_turnaround_time = 0;

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


scanf("%d", &n);

printf("\nEnter burst time for each process:\n");


for(i = 0; i < n; i++) {
printf("Process[%d]: ", i+1);
scanf("%d", &burst_time[i]);
remaining_time[i] = burst_time[i];
process[i] = i+1;
}

// Simulate SJF (Preemptive) algorithm


while(completed < n) {
smallest = INT_MAX;
for(i = 0; i < n; i++) {
if(remaining_time[i] > 0 && remaining_time[i] < smallest &&
current_time >= i) {
smallest = remaining_time[i];
j = i;
}
}
remaining_time[j]--;

if(remaining_time[j] == 0) {
completed++;
turnaround_time[j] = current_time+1;
waiting_time[j] = turnaround_time[j] - burst_time[j];
total_waiting_time += waiting_time[j];
total_turnaround_time += turnaround_time[j];
}
current_time++;
}

// Calculate average waiting time and average turnaround time


avg_waiting_time = total_waiting_time/n;
avg_turnaround_time = total_turnaround_time/n;

// Display results
printf("\nProcess\t Burst Time\t Waiting Time\t Turnaround Time\n");
for(i = 0; i < n; i++) {
printf("P[%d]\t %d\t\t %d\t\t %d\n", process[i], burst_time[i],
waiting_time[i], turnaround_time[i]);
}
printf("Average Waiting Time: %f\n", avg_waiting_time);
printf("Average Turnaround Time: %f\n", avg_turnaround_time);

return 0;
}

OUTPUT:
Enter the number of processes: 5

Enter burst time for each process:


Process[1]: 3
Process[2]: 5
Process[3]: 10
Process[4]: 9
Process[5]: 25

Process Burst Time Waiting Time Turnaround Time


P[1] 3 0 3
P[2] 5 3 8
P[3] 10 17 27
P[4] 9 8 17
P[5] 25 27 52
Average Waiting Time: 11.000000
Average Turnaround Time: 21.400000
PRIORITY CPU SCHEDULING
Exp. No.: 4(c) Date:
SOURCE CODE:
#include <stdio.h>

int main() {
int n, i, j, burst_time[20], waiting_time[20], turnaround_time[20],
priority[20], process[20], highest;
float avg_waiting_time = 0, avg_turnaround_time = 0, total_waiting_time = 0,
total_turnaround_time = 0;

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


scanf("%d", &n);

printf("\nEnter burst time and priority for each process:\n");


for(i = 0; i < n; i++) {
printf("Process[%d] Burst Time: ", i+1);
scanf("%d", &burst_time[i]);
printf("Process[%d] Priority: ", i+1);
scanf("%d", &priority[i]);
process[i] = i+1;
}

// Sort the processes by priority in descending order using selection sort


for(i = 0; i < n-1; i++) {
highest = i;
for(j = i+1; j < n; j++) {
if(priority[j] > priority[highest]) {
highest = j;
}
}
int temp = priority[i];
priority[i] = priority[highest];
priority[highest] = temp;

temp = burst_time[i];
burst_time[i] = burst_time[highest];
burst_time[highest] = temp;

temp = process[i];
process[i] = process[highest];
process[highest] = temp;
}

waiting_time[0] = 0;
// Calculate waiting time and turnaround time for each process
for(i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i-1] + burst_time[i-1];
turnaround_time[i] = waiting_time[i] + burst_time[i];
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}
// Calculate average waiting time and average turnaround time
avg_waiting_time = total_waiting_time/n;
avg_turnaround_time = total_turnaround_time/n;

// Display results
printf("\nProcess\t Burst Time\t Priority\t Waiting Time\t Turnaround
Time\n");
for(i = 0; i < n; i++) {
printf("P[%d]\t %d\t\t %d\t\t %d\t\t %d\n", process[i], burst_time[i],
priority[i], waiting_time[i], turnaround_time[i]);
}
printf("Average Waiting Time: %f\n", avg_waiting_time);
printf("Average Turnaround Time: %f\n", avg_turnaround_time);

return 0;
}

OUTPUT:
Enter the number of processes: 5

Enter burst time and priority for each process:


Process[1] Burst Time: 3
Process[1] Priority: 5
Process[2] Burst Time: 9
Process[2] Priority: 4
Process[3] Burst Time: 10
Process[3] Priority: 3
Process[4] Burst Time: 23
Process[4] Priority: 2
Process[5] Burst Time: 4
Process[5] Priority: 1

Process Burst Time Priority Waiting Time Turnaround Time


P[1] 3 5 0 0
P[2] 9 4 3 12
P[3] 10 3 12 22
P[4] 23 2 22 45
P[5] 4 1 45 49
Average Waiting Time: 16.400000
Average Turnaround Time: 25.600000
ROUND ROBIN CPU SCHEDULING
Exp. No.: 4(d) Date:
SOURCE CODE:
#include <stdio.h>

#define MAX 100

struct process {
int pid; // process id
int bt; // burst time
int wt; // waiting time
int tat; // turnaround time
int rt; // remaining time
};

void roundRobinScheduling(struct process p[], int n, int tq) {


int i, t = 0, completed = 0, j;
float avgwt = 0, avgtat = 0;

// Initialize remaining time with burst time


for (i = 0; i < n; i++)
p[i].rt = p[i].bt;

// Keep executing until all processes are completed


while (completed != n) {
for (i = 0; i < n; i++) {
if (p[i].rt > 0) {
if (p[i].rt > tq) {
t += tq;
p[i].rt -= tq;
} else {
t += p[i].rt;
p[i].wt = t - p[i].bt;
p[i].rt = 0;
p[i].tat = t;
completed++;
}
}
}
}

// Calculate average waiting and turnaround time


for (i = 0; i < n; i++) {
avgwt += p[i].wt;
avgtat += p[i].tat;
}

avgwt /= n;
avgtat /= n;

// Display process details


printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time");
for (i = 0; i < n; i++) {
printf("\nP%d\t\t%d\t\t%d\t\t%d", p[i].pid, p[i].bt, p[i].wt, p[i].tat);
}
printf("\n\nAverage Waiting Time: %f", avgwt);
printf("\nAverage Turnaround Time: %f", avgtat);
}

int main() {
int n, tq, i;
struct process p[MAX];

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


scanf("%d", &n);

printf("Enter time quantum: ");


scanf("%d", &tq);

printf("Enter burst time for each process:\n");


for (i = 0; i < n; i++) {
printf("Process[%d]: ", i + 1);
scanf("%d", &p[i].bt);
p[i].pid = i + 1;
}

roundRobinScheduling(p, n, tq);

return 0;
}

OUTPUT:
Enter the number of processes: 5
Enter time quantum: 25
Enter burst time for each process:
Process[1]: 3
Process[2]: 12
Process[3]: 9
Process[4]: 18
Process[5]: 7

Process Burst Time Waiting Time Turnaround Time


P1 3 0 3
P2 12 3 15
P3 9 15 24
P4 18 24 42
P5 7 42 49

Average Waiting Time: 16.799999


Average Turnaround Time: 26.600000
PRODUCER CONSUMER PROBLEM
Exp. No.: 5(a) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define BUFFER_SIZE 5
#define MAX_ITEMS 20

int buffer[BUFFER_SIZE];
int in = 0, out = 0, count = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;

int produce_item() {
static int item_num = 0;
return item_num++;
}

void insert_item(int item) {


buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
count++;
}

int remove_item() {
int item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
return item;
}

void consume_item(int item) {


printf("Consumed item %d\n", item);
}

void *producer(void *arg) {


int item;
while (1) {
item = produce_item();
pthread_mutex_lock(&mutex);
if (count == BUFFER_SIZE) {
pthread_cond_wait(&empty, &mutex);
}
insert_item(item);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&full);
printf("Produced item %d\n", item);
if (item == MAX_ITEMS) {
break;
}
}
pthread_exit(NULL);
}

void *consumer(void *arg) {


int item;
while (1) {
pthread_mutex_lock(&mutex);
if (count == 0) {
pthread_cond_wait(&full, &mutex);
}
item = remove_item();
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&empty);
consume_item(item);
if (item == MAX_ITEMS) {
break;
}
}
pthread_exit(NULL);
}

int main() {
pthread_t prod_thread, cons_thread;
pthread_create(&prod_thread, NULL, producer, NULL);
pthread_create(&cons_thread, NULL, consumer, NULL);
pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);
return 0;
}

OUTPUT:
Produced item 0
Produced item 1
Produced item 2
Produced item 3
Produced item 4
Produced item 5
Consumed item 0
Consumed item 1
Consumed item 2
Consumed item 3
Consumed item 4
Consumed item 5
Produced item 6
Produced item 7
Produced item 8
Produced item 9
Produced item 10
Produced item 11
Consumed item 6
Consumed item 7
Consumed item 8
Consumed item 9
Consumed item 10
Consumed item 11
Produced item 12
Produced item 13
Produced item 14
Produced item 15
Produced item 16
DINING PHILOSOPHERS PROBLEM
Exp. No.: 5(b) Date:
SOURCE CODE:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

#define N 5

pthread_mutex_t forks[N];
sem_t waiter;

void *philosopher(void *arg) {


int id = *(int *)arg;
int left_fork = id;
int right_fork = (id + 1) % N;

while (1) {
printf("Philosopher %d is thinking...\n", id);
sem_wait(&waiter);
pthread_mutex_lock(&forks[left_fork]);
printf("Philosopher %d picks up fork %d.\n", id, left_fork);
pthread_mutex_lock(&forks[right_fork]);
printf("Philosopher %d picks up fork %d.\n", id, right_fork);
printf("Philosopher %d is eating...\n", id);
pthread_mutex_unlock(&forks[left_fork]);
printf("Philosopher %d puts down fork %d.\n", id, left_fork);
pthread_mutex_unlock(&forks[right_fork]);
printf("Philosopher %d puts down fork %d.\n", id, right_fork);
sem_post(&waiter);
}
}

int main() {
pthread_t philosophers[N];
int ids[N];
sem_init(&waiter, 0, N - 1);
for (int i = 0; i < N; i++) {
ids[i] = i;
pthread_mutex_init(&forks[i], NULL);
pthread_create(&philosophers[i], NULL, philosopher, &ids[i]);
}
for (int i = 0; i < N; i++) {
pthread_join(philosophers[i], NULL);
}
for (int i = 0; i < N; i++) {
pthread_mutex_destroy(&forks[i]);
}
sem_destroy(&waiter);
return 0;
}
OUTPUT:
Philosopher 0 is thinking...
Philosopher 0 picks up fork 0.
Philosopher 0 picks up fork 1.
Philosopher 0 is eating...
Philosopher 0 puts down fork 0.
Philosopher 0 puts down fork 1.
Philosopher 0 is thinking...
Philosopher 0 picks up fork 0.
Philosopher 0 picks up fork 1.
Philosopher 0 is eating...
Philosopher 0 puts down fork 0.
Philosopher 0 puts down fork 1.
Philosopher 0 is thinking...
Philosopher 0 picks up fork 0.
Philosopher 0 picks up fork 1.
Philosopher 0 is eating...
Philosopher 0 puts down fork 0.
Philosopher 0 puts down fork 1.
Philosopher 0 is thinking...
Philosopher 0 picks up fork 0.
Philosopher 0 picks up fork 1.
Philosopher 0 is eating...
Philosopher 0 puts down fork 0.
Philosopher 0 puts down fork 1.
Philosopher 3 is thinking...
Philosopher 3 picks up fork 3.
Philosopher 3 picks up fork 4.
Philosopher 3 is eating...
Philosopher 3 puts down fork 3.
Philosopher 3 puts down fork 4.
Philosopher 3 is thinking...
Philosopher 3 picks up fork 3.
Philosopher 3 picks up fork 4.
Philosopher 3 is eating...
Philosopher 3 puts down fork 3.
Philosopher 3 puts down fork 4.
Philosopher 3 is thinking...
Philosopher 3 picks up fork 3.
Philosopher 3 picks up fork 4.
Philosopher 3 is eating...
Philosopher 3 puts down fork 3.
Philosopher 3 puts down fork 4.
Philosopher 3 is thinking...
Philosopher 3 picks up fork 3.
Philosopher 3 picks up fork 4.
Philosopher 3 is eating...
Philosopher 3 puts down fork 3.
Philosopher 3 puts down fork 4.
Philosopher 2 is thinking...
Philosopher 2 picks up fork 2.
Philosopher 2 picks up fork 3.
Philosopher 2 is eating...
Philosopher 2 puts down fork 2.
Philosopher 2 puts down fork 3.
Philosopher 2 is thinking...
Philosopher 2 picks up fork 2.
Philosopher 2 picks up fork 3.
Philosopher 2 is eating...
Philosopher 2 puts down fork 2.
Philosopher 2 puts down fork 3.
Philosopher 2 is thinking...
Philosopher 2 picks up fork 2.
Philosopher 2 picks up fork 3.
Philosopher 2 is eating...
Philosopher 2 puts down fork 2.
Philosopher 2 puts down fork 3.
Philosopher 2 is thinking...
Philosopher 2 picks up fork 2.
Philosopher 2 picks up fork 3.
Philosopher 2 is eating...
Philosopher 2 puts down fork 2.
Philosopher 2 puts down fork 3.
Philosopher 4 is thinking...
Philosopher 4 picks up fork 4.
BANKER’S ALGORITHM FOR DEADLOCK AVOIDANCE
Exp. No.: 6 Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>

#define MAX_PROCESS 10
#define MAX_RESOURCE 10

int main()
{
int i, j, k, process_count, resource_count;
int available[MAX_RESOURCE], max[MAX_PROCESS][MAX_RESOURCE],
allocation[MAX_PROCESS][MAX_RESOURCE], need[MAX_PROCESS][MAX_RESOURCE];
int work[MAX_RESOURCE], finish[MAX_PROCESS], safe_seq[MAX_PROCESS];

// input the number of processes and resources


printf("Enter the number of processes: ");
scanf("%d", &process_count);
printf("Enter the number of resources: ");
scanf("%d", &resource_count);

// input the available resources


printf("Enter the number of available resources for each type:\n");
for (i = 0; i < resource_count; i++)
scanf("%d", &available[i]);

// input the maximum needs of each process


printf("Enter the maximum needs of each process:\n");
for (i = 0; i < process_count; i++)
{
printf("Process %d: ", i);
for (j = 0; j < resource_count; j++)
scanf("%d", &max[i][j]);
}

// input the allocated resources for each process


printf("Enter the allocated resources for each process:\n");
for (i = 0; i < process_count; i++)
{
printf("Process %d: ", i);
for (j = 0; j < resource_count; j++)
{
scanf("%d", &allocation[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
finish[i] = 0; // initialize all processes as unfinished
}

// initialize the work array


for (i = 0; i < resource_count; i++)
work[i] = available[i];
// check for safe sequence
int count = 0;
while (count < process_count)
{
int found = 0;
for (i = 0; i < process_count; i++)
{
if (finish[i] == 0)
{
int j;
for (j = 0; j < resource_count; j++)
{
if (need[i][j] > work[j])
break;
}
if (j == resource_count)
{
for (k = 0; k < resource_count; k++)
work[k] += allocation[i][k];
finish[i] = 1;
safe_seq[count] = i;
count++;
found = 1;
}
}
}
if (found == 0)
break;
}

if (count == process_count)
{
printf("\nSafe Sequence: ");
for (i = 0; i < process_count; i++)
printf("%d ", safe_seq[i]);
printf("\n");
}
else
{
printf("\nNo Safe Sequence\n");
return 0;
}

// check for deadlock with changed maximum request of one process


int process_id, request[MAX_RESOURCE];
printf("\nEnter the process ID for which the maximum request is to be
changed: ");
scanf("%d", &process_id);
printf("Enter the new maximum request for process %d: ", process_id);
for (i = 0; i < resource_count; i++)
scanf("%d", &request[i]);

// check if the new maximum request can be satisfied


for (i = 0; i < resource_count; i++)
{
if (request[i] > max[process_id][i] || request[i] > available[i])
{
printf("\nNew maximum request cannot be satisfied.\n");
return 0;
}
}

// simulate allocation of new maximum request and check for deadlock


for (i = 0; i < resource_count; i++)
{
available[i] -= request[i];
allocation[process_id][i] += request[i];
need[process_id][i] -= request[i];
}

for (i = 0; i < resource_count; i++)


work[i] = available[i];

count = 0;
while (count < process_count)
{
int found = 0;
for (i = 0; i < process_count; i++)
{
if (finish[i] == 0)
{
int j;
for (j = 0; j < resource_count; j++)
{
if (need[i][j] > work[j])
break;
}
if (j == resource_count)
{
for (k = 0; k < resource_count; k++)
work[k] += allocation[i][k];
finish[i] = 1;
count++;
found = 1;
}
}
}
if (found == 0)
break;
}

if (count == process_count)
printf("\nNo deadlock with new maximum request.\n");
else
printf("\nDeadlock detected with new maximum request.\n");

return 0;
}

OUTPUT:
Enter the number of processes: 5
Enter the number of resources: 3
Enter the number of available resources for each type:
7 8 10
Enter the maximum needs of each process:
Process 0: 3 4 3
Process 1: 2 0 0
Process 2: 6 5 7
Process 3: 7 5 6
Process 4: 2 0 1
Enter the allocated resources for each process:
Process 0: 9 7 3
Process 1: 6 0 1
Process 2: 2 0 8
Process 3: 8 0 0
Process 4: 7 9 3

Safe Sequence: 0 1 2 3 4

Enter the process ID for which the maximum request is to be changed: 3


Enter the new maximum request for process 3: 9 8 7

New maximum request cannot be satisfied.


FIRST FIT MEMORY ALLOCATION ALGORITHM
Exp. No.: 7(a) Date:
SOURCE CODE:
#include <stdio.h>

#define MAX_BLOCKS 100


#define MAX_PROCESS 100

void firstFit(int blockSize[], int m, int processSize[], int n)


{
int allocation[MAX_PROCESS];

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


{
allocation[i] = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
allocation[i] = j;
blockSize[j] -= processSize[i];
break;
}
}
}

printf("\nProcess 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 blockSize[MAX_BLOCKS], processSize[MAX_PROCESS];
int m, n;

printf("Enter the number of memory blocks: ");


scanf("%d", &m);

printf("Enter the size of each memory block:\n");


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:\n");


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

firstFit(blockSize, m, processSize, n);

return 0;
}

OUTPUT:
Enter the number of memory blocks: 5
Enter the size of each memory block:
45
20
50
25
10
Enter the number of processes: 5
Enter the size of each process:
50
19
34
20
9

Process No. Process Size Block no.


1 50 3
2 19 1
3 34 Not Allocated
4 20 1
5 9 2
BEST FIT MEMORY ALLOCATION ALGORITHM
Exp. No.: 7(b) Date:
SOURCE CODE:
#include <stdio.h>

#define MAX_BLOCKS 100


#define MAX_PROCESS 100

void bestFit(int blockSize[], int m, int processSize[], int n)


{
int allocation[MAX_PROCESS];

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


{
allocation[i] = -1;
int bestIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx])
bestIdx = j;
}
}

if (bestIdx != -1)
{
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
}
}

printf("\nProcess 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 blockSize[MAX_BLOCKS], processSize[MAX_PROCESS];
int m, n;

printf("Enter the number of memory blocks: ");


scanf("%d", &m);

printf("Enter the size of each memory block:\n");


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:\n");


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

bestFit(blockSize, m, processSize, n);

return 0;
}

OUTPUT:
Enter the size of each memory block:
45
20
50
25
10
Enter the number of processes: 5
Enter the size of each process:
50
19
34
20
9

Process No. Process Size Block no.


1 50 3
2 19 2
3 34 1
4 20 4
5 9 5
WORST FIT MEMORY ALLOCATION ALGORITHM
Exp. No.: 7(c) Date:
SOURCE CODE:
#include <stdio.h>

#define MAX_BLOCKS 100


#define MAX_PROCESS 100

void worstFit(int blockSize[], int m, int processSize[], int n)


{
int allocation[MAX_PROCESS];

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


{
allocation[i] = -1;
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)
{
allocation[i] = worstIdx;
blockSize[worstIdx] -= processSize[i];
}
}

printf("\nProcess 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 blockSize[MAX_BLOCKS], processSize[MAX_PROCESS];
int m, n;

printf("Enter the number of memory blocks: ");


scanf("%d", &m);

printf("Enter the size of each memory block:\n");


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:\n");


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

worstFit(blockSize, m, processSize, n);

return 0;
}

OUTPUT:
Enter the number of memory blocks: 5
Enter the size of each memory block:
50
35
78
24
10
Enter the number of processes: 5
Enter the size of each process:
51
30
76
20
9

Process No. Process Size Block no.


1 51 3
2 30 1
3 76 Not Allocated
4 20 2
5 9 3
FIRST IN, FIRST OUT (FIFO) - PAGE REPLACEMENT ALGORITHM
Exp. No.: 8(a) Date:
SOURCE CODE:
#include <stdio.h>

#define MAX_FRAMES 80
#define MAX_PAGES 80

void fifo(int pages[], int n, int frames, int pageFaults[])


{
int memory[MAX_FRAMES];
int rear = -1;
int front = -1;

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


{
int page = pages[i];
int found = 0;

// Check if the page is already in memory


for (int j = 0; j <= rear; j++)
{
if (memory[j] == page)
{
found = 1;
break;
}
}

// Page fault, page needs to be brought into memory


if (!found)
{
// Check if memory is full
if (rear < frames - 1)
{
memory[++rear] = page;
}
else
{
// Remove the oldest page from the front
front = (front + 1) % frames;
memory[front] = page;
}

pageFaults[i] = 1;
}
else
{
pageFaults[i] = 0;
}
}
}
int main()
{
int pages[MAX_PAGES];
int n, frames;

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


scanf("%d", &n);

printf("Enter the page reference string:\n");


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

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


scanf("%d", &frames);

int pageFaults[MAX_PAGES];
fifo(pages, n, frames, pageFaults);

printf("\nPage Faults:\n");
for (int i = 0; i < n; i++)
{
printf("Page %d: %s\n", pages[i], (pageFaults[i] == 1) ? "Fault" : "No
Fault");
}

return 0;
}

OUTPUT:
Enter the number of pages: 12
Enter the page reference string:
2 3 4 2 1 3 7 5 4 3 2 5
Enter the number of frames: 3

Page Faults:
Page 2: Fault
Page 3: Fault
Page 4: Fault
Page 2: No Fault
Page 1: Fault
Page 3: No Fault
Page 7: Fault
Page 5: Fault
Page 4: Fault
Page 3: Fault
Page 2: Fault
Page 5: Fault
LEAST FREQUENTLY USED (LFU) - PAGE REPLACEMENT ALGORITHM
Exp. No.: 8(b) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>

#define MAX_FRAMES 70
#define MAX_PAGES 70

typedef struct
{
int pageNumber;
int frequency;
int lastUsed;
} Page;

void lfu(int pages[], int n, int frames, int pageFaults[])


{
Page memory[MAX_FRAMES];
int memoryCount = 0;

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


{
int page = pages[i];
bool found = false;

// Check if the page is already in memory


for (int j = 0; j < memoryCount; j++)
{
if (memory[j].pageNumber == page)
{
memory[j].frequency++;
memory[j].lastUsed = i;
found = true;
break;
}
}

// Page fault, page needs to be brought into memory


if (!found)
{
// Check if memory is full
if (memoryCount < frames)
{
memory[memoryCount].pageNumber = page;
memory[memoryCount].frequency = 1;
memory[memoryCount].lastUsed = i;
memoryCount++;
}
else
{
// Find the least frequently used page
int leastFreqIdx = 0;
for (int j = 1; j < memoryCount; j++)
{
if (memory[j].frequency < memory[leastFreqIdx].frequency ||
(memory[j].frequency == memory[leastFreqIdx].frequency &&
memory[j].lastUsed < memory[leastFreqIdx].lastUsed))
{
leastFreqIdx = j;
}
}

// Replace the least frequently used page


memory[leastFreqIdx].pageNumber = page;
memory[leastFreqIdx].frequency = 1;
memory[leastFreqIdx].lastUsed = i;
}

pageFaults[i] = 1;
}
else
{
pageFaults[i] = 0;
}
}
}

int main()
{
int pages[MAX_PAGES];
int n, frames;

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


scanf("%d", &n);

printf("Enter the page reference string:\n");


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

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


scanf("%d", &frames);

int pageFaults[MAX_PAGES];
lfu(pages, n, frames, pageFaults);

printf("\nPage Faults:\n");
for (int i = 0; i < n; i++)
{
printf("Page %d: %s\n", pages[i], (pageFaults[i] == 1) ? "Fault" : "No
Fault");
}

return 0;
}

OUTPUT:
Enter the number of pages: 12
Enter the page reference string:
2 3 4 2 1 3 7 5 4 3 2 5
Enter the number of frames: 3

Page Faults:
Page 2: Fault
Page 3: Fault
Page 4: Fault
Page 2: No Fault
Page 1: Fault
Page 3: Fault
Page 7: Fault
Page 5: Fault
Page 4: Fault
Page 3: Fault
Page 2: No Fault
Page 5: Fault
LEAST RECENTLY USED (LRU) - PAGE REPLACEMENT ALGORITHM
Exp. No.: 8(c) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>

#define MAX_FRAMES 70
#define MAX_PAGES 70

void lru(int pages[], int n, int frames, int pageFaults[])


{
int memory[MAX_FRAMES];
int lastUsed[MAX_FRAMES];
int memoryCount = 0;

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


{
int page = pages[i];
bool found = false;

// Check if the page is already in memory


for (int j = 0; j < memoryCount; j++)
{
if (memory[j] == page)
{
found = true;
lastUsed[j] = i;
break;
}
}

// Page fault, page needs to be brought into memory


if (!found)
{
// Check if memory is full
if (memoryCount < frames)
{
memory[memoryCount] = page;
lastUsed[memoryCount] = i;
memoryCount++;
}
else
{
// Find the least recently used page
int leastUsedIdx = 0;
for (int j = 1; j < memoryCount; j++)
{
if (lastUsed[j] < lastUsed[leastUsedIdx])
{
leastUsedIdx = j;
}
}
// Replace the least recently used page
memory[leastUsedIdx] = page;
lastUsed[leastUsedIdx] = i;
}

pageFaults[i] = 1;
}
else
{
pageFaults[i] = 0;
}
}
}

int main()
{
int pages[MAX_PAGES];
int n, frames;

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


scanf("%d", &n);

printf("Enter the page reference string:\n");


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

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


scanf("%d", &frames);

int pageFaults[MAX_PAGES];
lru(pages, n, frames, pageFaults);

printf("\nPage Faults:\n");
for (int i = 0; i < n; i++)
{
printf("Page %d: %s\n", pages[i], (pageFaults[i] == 1) ? "Fault" : "No
Fault");
}

return 0;
}
OUTPUT:
Enter the number of pages: 12
Enter the page reference string:
2 3 4 2 1 3 7 5 4 3 2 5
Enter the number of frames: 3

Page Faults:
Page 2: Fault
Page 3: Fault
Page 4: Fault
Page 2: No Fault
Page 1: Fault
Page 3: Fault
Page 7: Fault
Page 5: Fault
Page 4: Fault
Page 3: Fault
Page 2: Fault
Page 5: Fault
OPTIMAL - PAGE REPLACEMENT ALGORITHM
Exp. No.: 8(d) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>

#define MAX_FRAMES 100


#define MAX_PAGES 100
#define INFINITY 999999

int getNextReference(int pages[], int n, int currentIndex)


{
for (int i = currentIndex + 1; i < n; i++)
{
if (pages[i] == pages[currentIndex])
return i;
}
return INFINITY; // If no future reference found, return a large value
}

void optimal(int pages[], int n, int frames, int pageFaults[])


{
int memory[MAX_FRAMES];
bool isPresent[MAX_FRAMES];
int memoryCount = 0;

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


{
int page = pages[i];
bool found = false;

// Check if the page is already in memory


for (int j = 0; j < memoryCount; j++)
{
if (memory[j] == page)
{
found = true;
break;
}
}

// Page fault, page needs to be brought into memory


if (!found)
{
// Check if memory is full
if (memoryCount < frames)
{
memory[memoryCount] = page;
isPresent[memoryCount] = true;
memoryCount++;
}
else
{
// Find the page that will not be used for the longest duration
int index = -1;
int farthest = -1;
for (int j = 0; j < memoryCount; j++)
{
int nextReference = getNextReference(pages, n, i);
if (nextReference > farthest)
{
farthest = nextReference;
index = j;
}
}

// Replace the page that will not be used for the longest
duration
memory[index] = page;
isPresent[index] = true;
}

pageFaults[i] = 1;
}
else
{
pageFaults[i] = 0;
}
}
}

int main()
{
int pages[MAX_PAGES];
int n, frames;

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


scanf("%d", &n);

printf("Enter the page reference string:\n");


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

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


scanf("%d", &frames);

int pageFaults[MAX_PAGES];
optimal(pages, n, frames, pageFaults);

printf("\nPage Faults:\n");
for (int i = 0; i < n; i++)
{
printf("Page %d: %s\n", pages[i], (pageFaults[i] == 1) ? "Fault" : "No
Fault");
}

return 0;
}

OUTPUT:
Enter the number of pages: 12
Enter the page reference string:
2 3 4 2 1 3 7 5 4 3 2 5
Enter the number of frames: 3

Page Faults:
Page 2: Fault
Page 3: Fault
Page 4: Fault
Page 2: No Fault
Page 1: Fault
Page 3: No Fault
Page 7: Fault
Page 5: Fault
Page 4: No Fault
Page 3: No Fault
Page 2: Fault
Page 5: Fault
FIRST COME FIRST SEARCH (FCFS) - DISK SCHEDULING ALGORITHM
Exp. No.: 9(a) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>

void fcfs(int requests[], int n, int start)


{
int totalSeekTime = 0;
int currentPos = start;

printf("Sequence of disk access:\n");


printf("%d", currentPos);

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


{
int diff = abs(requests[i] - currentPos);
totalSeekTime += diff;
currentPos = requests[i];

printf(" -> %d", currentPos);


}

printf("\nTotal Seek Time: %d\n", totalSeekTime);


double avgSeekTime = (double)totalSeekTime / n;
printf("Average Seek Time: %.2lf\n", avgSeekTime);
}

int main()
{
int requests[100];
int n, start;

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


scanf("%d", &n);

printf("Enter the requests:\n");


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

printf("Enter the starting position: ");


scanf("%d", &start);

fcfs(requests, n, start);

return 0;
}
OUTPUT:
Enter the number of requests: 5
Enter the requests:
98
183
37
122
14
Enter the starting position: 53
Sequence of disk access:
53 -> 98 -> 183 -> 37 -> 122 -> 14
Total Seek Time: 469
Average Seek Time: 93.80
SHORTEST SEEK TIME FIRST (SSTF) - DISK SCHEDULING ALGORITHM
Exp. No.: 9(b) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>

int findClosestRequest(int requests[], bool visited[], int n, int currentPos)


{
int minDistance = INT_MAX;
int closestIndex = -1;

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


{
int distance = abs(requests[i] - currentPos);
if (!visited[i] && distance < minDistance)
{
minDistance = distance;
closestIndex = i;
}
}

return closestIndex;
}

void sstf(int requests[], int n, int start)


{
int totalSeekTime = 0;
int currentPos = start;
bool visited[100] = {false};

printf("Sequence of disk access:\n");


printf("%d", currentPos);

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


{
int closestIndex = findClosestRequest(requests, visited, n, currentPos);
visited[closestIndex] = true;

int closestRequest = requests[closestIndex];


totalSeekTime += abs(closestRequest - currentPos);
currentPos = closestRequest;

printf(" -> %d", currentPos);


}

printf("\nTotal Seek Time: %d\n", totalSeekTime);


double avgSeekTime = (double)totalSeekTime / n;
printf("Average Seek Time: %.2lf\n", avgSeekTime);
}
int main()
{
int requests[100];
int n, start;

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


scanf("%d", &n);

printf("Enter the requests:\n");


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

printf("Enter the starting position: ");


scanf("%d", &start);

sstf(requests, n, start);

return 0;
}

OUTPUT:
Enter the number of requests: 5
Enter the requests:
98
183
37
122
14
Enter the starting position: 53
Sequence of disk access:
53 -> 37 -> 14 -> 98 -> 122 -> 183
Total Seek Time: 208
Average Seek Time: 41.60
SCAN (ELEVATOR)- DISK SCHEDULING ALGORITHM
Exp. No.: 9(c) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void scan(int requests[], int n, int start, int direction, int maxCylinders)
{
int totalSeekTime = 0;
int currentPos = start;
int minCylinder = 0;
int maxCylinder = maxCylinders - 1;
bool visited[100] = {false};

printf("Sequence of disk access:\n");

// Move towards the end of the disk


if (direction == 1)
{
for (int i = currentPos; i <= maxCylinder; i++)
{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}

// Change direction and move towards the other end of the disk
direction = -1;
printf("|\n");

for (int i = maxCylinder; i >= minCylinder; i--)


{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}
}
// Move towards the beginning of the disk
else
{
for (int i = currentPos; i >= minCylinder; i--)
{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}

// Change direction and move towards the other end of the disk
direction = 1;
printf("|\n");

for (int i = minCylinder; i <= maxCylinder; i++)


{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}
}

printf("\nTotal Seek Time: %d\n", totalSeekTime);


double avgSeekTime = (double)totalSeekTime / n;
printf("Average Seek Time: %.2lf\n", avgSeekTime);
}

int main()
{
int requests[100];
int n, start, maxCylinders, direction;

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


scanf("%d", &n);

printf("Enter the requests:\n");


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

printf("Enter the starting position: ");


scanf("%d", &start);

printf("Enter the maximum number of cylinders: ");


scanf("%d", &maxCylinders);

printf("Enter the initial direction (1 for towards the end, -1 for towards
the beginning): ");
scanf("%d", &direction);

scan(requests, n, start, direction, maxCylinders);


return 0;
}

OUTPUT:
Enter the number of requests: 6
Enter the requests:
20
89
42
6
57
92
Enter the starting position: 50
Enter the maximum number of cylinders: 200
Enter the initial direction (1 for towards the end, -1 for towards the
beginning): 1
Sequence of disk access:
50 -> 51 -> 52 -> 53 -> 54 -> 55 -> 56 -> 57 -> 58 -> 59 -> 60 -> 61 -> 62 -> 63
-> 64 -> 65 -> 66 -> 67 -> 68 -> 69 -> 70 -> 71 -> 72 -> 73 -> 74 -> 75 -> 76 ->
77 -> 78 -> 79 -> 80 -> 81 -> 82 -> 83 -> 84 -> 85 -> 86 -> 87 -> 88
-> 89 -> 90 -> 91 -> 92 -> 93 -> 94 -> 95 -> 96 -> 97 -> 98 -> 99 -> 100 -> 102 -
> 103 -> 104 -> 105 -> 106 -> 107 -> 108 -> 109 -> 110 -> 111 -> 112 -> |1 -> 0 -
>
Total Seek Time: 174
Average Seek Time: 29.00
CIRCULAR SCAN (CSCAN) - DISK SCHEDULING ALGORITHM
Exp. No.: 9(d) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void cscan(int requests[], int n, int start, int direction, int maxCylinders)
{
int totalSeekTime = 0;
int currentPos = start;
int minCylinder = 0;
int maxCylinder = maxCylinders - 1;
bool visited[100] = {false};

printf("Sequence of disk access:\n");

// Move towards the end of the disk


if (direction == 1)
{
for (int i = currentPos; i <= maxCylinder; i++)
{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}

// Move to the beginning of the disk


for (int i = minCylinder; i <= currentPos; i++)
{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}
}
// Move towards the beginning of the disk
else
{
for (int i = currentPos; i >= minCylinder; i--)
{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}

// Move to the end of the disk


for (int i = maxCylinder; i >= currentPos; i--)
{
if (!visited[i])
{
printf("%d -> ", i);
visited[i] = true;
totalSeekTime += abs(i - currentPos);
currentPos = i;
}
}
}

printf("\nTotal Seek Time: %d\n", totalSeekTime);


double avgSeekTime = (double)totalSeekTime / n;
printf("Average Seek Time: %.2lf\n", avgSeekTime);
}

int main()
{
int requests[100];
int n, start, maxCylinders, direction;

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


scanf("%d", &n);

printf("Enter the requests:\n");


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

printf("Enter the starting position: ");


scanf("%d", &start);

printf("Enter the maximum number of cylinders: ");


scanf("%d", &maxCylinders);

printf("Enter the initial direction (1 for towards the end, -1 for towards
the beginning): ");
scanf("%d", &direction);

cscan(requests, n, start, direction, maxCylinders);

return 0;
}
OUTPUT:
Enter the number of requests: 6
Enter the requests:
50
30
75
10
100
25
Enter the starting position: 60
Enter the maximum number of cylinders: 200
Enter the initial direction (1 for towards the end, -1 for towards the
beginning): 1
Sequence of disk access:
60 -> 61 -> 62 -> 63 -> 64 -> 65 -> 66 -> 67 -> 68 -> 69 -> 70 -> 71 -> 72 -> 73
-> 74 -> 75 -> 76 -> 77 -> 78 -> 79 -> 80 -> 81 -> 82 -> 83 -> 84 -> 85 -> 86 ->
87 -> 88 -> 89 -> 90 -> 91 -> 92 -> 93 -> 94 -> 95 -> 96 -> 97 -> 98
-> 99 -> 100 -> 102 -> 103 -> 104 -> 105 -> 106 -> 107 -> 108 -> 109 -> 110 ->
111 -> 112 -> 0 ->
Total Seek Time: 164
Average Seek Time: 27.33
CONTIGUOUS ALLOCATION STRATEGIES
Exp. No.: 10(a) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_FILES 20

struct File
{
int fileId;
int startingBlock;
int fileSize;
};

struct Disk
{
int totalBlocks;
bool allocatedBlocks[MAX_FILES];
};

void initializeDisk(struct Disk *disk, int totalBlocks)


{
disk->totalBlocks = totalBlocks;
for (int i = 0; i < MAX_FILES; i++)
{
disk->allocatedBlocks[i] = false;
}
}

bool allocateFile(struct Disk *disk, struct File *file)


{
int remainingBlocks = disk->totalBlocks;
for (int i = 0; i < MAX_FILES; i++)
{
if (!disk->allocatedBlocks[i])
{
int j;
for (j = file->startingBlock; j < (file->startingBlock + file-
>fileSize); j++)
{
if (disk->allocatedBlocks[j])
{
break;
}
}
if (j == (file->startingBlock + file->fileSize))
{
// Allocate blocks
for (int k = file->startingBlock; k < (file->startingBlock +
file->fileSize); k++)
{
disk->allocatedBlocks[k] = true;
remainingBlocks--;
}
file->fileId = i;
return true;
}
}
}
if (remainingBlocks < file->fileSize)
{
printf("Not enough contiguous blocks available.\n");
}
return false;
}

void printDiskStatus(struct Disk *disk)


{
printf("Disk Status:\n");
printf("Total Blocks: %d\n", disk->totalBlocks);
printf("Allocated Blocks:\n");
for (int i = 0; i < disk->totalBlocks; i++)
{
printf("%d: %s\n", i, disk->allocatedBlocks[i] ? "Allocated" : "Free");
}
}

int main()
{
struct Disk disk;
initializeDisk(&disk, 20);

struct File files[5] = {


{0, 10, 5}, // File 0: Starting block = 10, Size = 5
{0, 30, 10}, // File 1: Starting block = 30, Size = 10
{0, 50, 6}, // File 2: Starting block = 50, Size = 6
{0, 80, 8}, // File 3: Starting block = 80, Size = 8
{0, 5, 15} // File 4: Starting block = 5, Size = 15
};

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


{
if (allocateFile(&disk, &files[i]))
{
printf("File %d allocated successfully.\n", i);
}
else
{
printf("File %d allocation failed.\n", i);
}
}

printDiskStatus(&disk);
return 0;
}

OUTPUT:
File 0 allocated successfully.
File 1 allocation failed.
File 2 allocation failed.
File 3 allocated successfully.
File 4 allocation failed.
Disk Status:
Total Blocks: 20
Allocated Blocks:
0: Free
1: Free
2: Free
3: Free
4: Free
5: Free
6: Free
7: Free
8: Free
9: Free
10: Allocated
11: Allocated
12: Allocated
13: Allocated
14: Allocated
15: Free
16: Free
17: Free
18: Free
19: Free
LINKED ALLOCATION STRATEGIES
Exp. No.: 10(b) Date:
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_FILES 20

struct File
{
int fileId;
int startingBlock;
int fileSize;
int *blockPointers;
};

struct Disk
{
int totalBlocks;
bool allocatedBlocks[MAX_FILES];
};

void initializeDisk(struct Disk *disk, int totalBlocks)


{
disk->totalBlocks = totalBlocks;
for (int i = 0; i < MAX_FILES; i++)
{
disk->allocatedBlocks[i] = false;
}
}

bool allocateFile(struct Disk *disk, struct File *file)


{
int remainingBlocks = disk->totalBlocks;
int requiredBlocks = file->fileSize;

if (requiredBlocks > remainingBlocks)


{
printf("Not enough blocks available on the disk.\n");
return false;
}

int *blockPointers = (int *)malloc(requiredBlocks * sizeof(int));


if (blockPointers == NULL)
{
printf("Memory allocation failed.\n");
return false;
}

int allocatedBlocksCount = 0;
int currentBlock = -1;
for (int i = 0; i < disk->totalBlocks; i++)
{
if (!disk->allocatedBlocks[i])
{
if (currentBlock == -1)
{
file->startingBlock = i;
}
else
{
blockPointers[currentBlock] = i;
}

currentBlock = i;
disk->allocatedBlocks[i] = true;
allocatedBlocksCount++;

if (allocatedBlocksCount == requiredBlocks)
{
break;
}
}
}

if (allocatedBlocksCount == requiredBlocks)
{
blockPointers[currentBlock] = -1;
file->blockPointers = blockPointers;
file->fileId = file->startingBlock;
return true;
}
else
{
printf("Not enough consecutive blocks available on the disk.\n");
free(blockPointers);
return false;
}
}

void printDiskStatus(struct Disk *disk)


{
printf("Disk Status:\n");
printf("Total Blocks: %d\n", disk->totalBlocks);
printf("Allocated Blocks:\n");
for (int i = 0; i < disk->totalBlocks; i++)
{
printf("%d: %s\n", i, disk->allocatedBlocks[i] ? "Allocated" : "Free");
}
}

int main()
{
struct Disk disk;
initializeDisk(&disk, 20);

struct File files[5] = {


{0, 0, 5}, // File 0: Size = 5
{0, 10, 10}, // File 1: Size = 10
{0, 30, 6}, // File 2: Size = 6
{0, 50, 8}, // File 3: Size = 8
{0, 70, 15} // File 4: Size = 15
};

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


{
if (allocateFile(&disk, &files[i]))
{
printf("File %d allocated successfully.\n", i);
}
else
{
printf("File %d allocation failed.\n", i);
}
}

printDiskStatus(&disk);

return 0;
}

OUTPUT:
File 0 allocated successfully.
File 1 allocated successfully.
Not enough consecutive blocks available on the disk.
File 2 allocation failed.
Not enough consecutive blocks available on the disk.
File 3 allocation failed.
Not enough consecutive blocks available on the disk.
File 4 allocation failed.
Disk Status:
Total Blocks: 20
Allocated Blocks:
0: Allocated
1: Allocated
2: Allocated
3: Allocated
4: Allocated
5: Allocated
6: Allocated
7: Allocated
8: Allocated
9: Allocated
10: Allocated
11: Allocated
12: Allocated
13: Allocated
14: Allocated
15: Allocated
16: Allocated
17: Allocated
18: Allocated
19: Allocated

You might also like