0% found this document useful (0 votes)
6 views40 pages

Gpcet OS Lab Manual

The document provides code implementations for various CPU scheduling algorithms including FCFS, SJF, Priority, and Round Robin, along with semaphore and monitor-based control for managing ports. It also includes examples of concurrent thread execution using pthreads and a solution to the producer-consumer problem using semaphores. Each section contains C code snippets demonstrating the respective concepts and their outputs.

Uploaded by

mohammedsureim
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)
6 views40 pages

Gpcet OS Lab Manual

The document provides code implementations for various CPU scheduling algorithms including FCFS, SJF, Priority, and Round Robin, along with semaphore and monitor-based control for managing ports. It also includes examples of concurrent thread execution using pthreads and a solution to the producer-consumer problem using semaphores. Each section contains C code snippets demonstrating the respective concepts and their outputs.

Uploaded by

mohammedsureim
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

4.

Simulate the following CPU scheduling algorithms


a) FCFS b)SJF c)Priority d)Round Robin
a) FCFS
#include <stdio.h>
int main()
{
int n, i;
int bt[20], wt[20], tat[20];
float avg_wt = 0, avg_tat = 0;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter burst times:\n");
for(i = 0; i < n; i++) {
printf("P%d: ", i+1);
scanf("%d", &bt[i]);
}
// Waiting time for first process is 0
wt[0] = 0;
// Calculate waiting time
for(i = 1; i < n; i++)
wt[i] = wt[i-1] + bt[i-1];
// Calculate turnaround time
for(i = 0; i < n; i++)
tat[i] = wt[i] + bt[i];
// Display results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++)
{
printf("P%d\t%d\t\t%d\t\t%d\n", i+1, bt[i], wt[i], tat[i]);
avg_wt += wt[i];
avg_tat += tat[i];
}
printf("\nAverage Waiting Time = %.2f", avg_wt/n);
printf("\nAverage Turnaround Time = %.2f\n", avg_tat/n);
return 0;
}
Output: Enter number of processes: 4
Enter burst times:
P1: 5
P2: 3
P3: 8
P4: 6

Process Burst Time Waiting Time Turnaround Time


P1 5 0 5
P2 3 5 8
P3 8 8 16
P4 6 16 22
Average Waiting Time = 7.25
Average Turnaround Time = 12.75

b)SJF
#include <stdio.h>
int main()
{
int n, i, j;
int bt[20], wt[20], tat[20], p[20];
float avg_wt = 0, avg_tat = 0;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter burst times:\n");
for(i = 0; i < n; i++)
{
printf("P%d: ", i+1);
scanf("%d", &bt[i]);
p[i] = i+1; // Process number
}
// Sort processes by burst time
for(i = 0; i < n-1; i++)
{
for(j = i+1; j < n; j++)
{
if(bt[i] > bt[j])
{
int temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
wt[0] = 0;
// Calculate waiting time
for(i = 1; i < n; i++)
wt[i] = wt[i-1] + bt[i-1];
// Calculate turnaround time
for(i = 0; i < n; i++)
tat[i] = wt[i] + bt[i];
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++)
{
printf("P%d\t%d\t\t%d\t\t%d\n", p[i], bt[i], wt[i], tat[i]);
avg_wt += wt[i];
avg_tat += tat[i];
}
printf("\nAverage Waiting Time = %.2f", avg_wt/n);
printf("\nAverage Turnaround Time = %.2f\n", avg_tat/n);
return 0;
}
OutPut:
Enter number of processes: 4
Enter burst times:
P1: 6
P2: 8
P3: 7
P4: 3

Process Burst Time Waiting Time Turnaround Time


P4 3 0 3
P1 6 3 9
P3 7 9 16
P2 8 16 24

Average Waiting Time = 7.00


Average Turnaround Time = 13.00

c)Priority
#include <stdio.h>
int main()
{
int n, i, j;
int bt[20], wt[20], tat[20], p[20], pr[20];
float avg_wt = 0, avg_tat = 0;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter Burst Time and Priority:\n");
for(i = 0; i < n; i++)
{
printf("P%d Burst Time: ", i+1);
scanf("%d", &bt[i]);
printf("P%d Priority: ", i+1);
scanf("%d", &pr[i]);
p[i] = i+1;
}
// Sort by priority
for(i = 0; i < n-1; i++)
{
for(j = i+1; j < n; j++)
{
if(pr[i] > pr[j])
{ // smaller number = higher priority
int temp;
temp = pr[i];
pr[i] = pr[j];
pr[j] = temp;
temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
wt[0] = 0;
// Calculate Waiting Time
for(i = 1; i < n; i++)
wt[i] = wt[i-1] + bt[i-1];
// Calculate Turnaround Time
for(i = 0; i < n; i++)
tat[i] = wt[i] + bt[i];
printf("\nProcess\tBurst\tPriority\tWaiting\tTurnaround\n");
for(i = 0; i < n; i++)
{
printf("P%d\t%d\t%d\t\t%d\t%d\n", p[i], bt[i], pr[i], wt[i], tat[i]);
avg_wt += wt[i];
avg_tat += tat[i];
}
printf("\nAverage Waiting Time = %.2f", avg_wt/n);
printf("\nAverage Turnaround Time = %.2f\n", avg_tat/n);
return 0;
}
OutPut:
Enter number of processes: 4
Enter Burst Time and Priority:
P1 Burst Time: 5
P1 Priority: 2
P2 Burst Time: 3
P2 Priority: 1
P3 Burst Time: 8
P3 Priority: 4
P4 Burst Time: 6
P4 Priority: 3

Process Burst Priority Waiting Turnaround


P2 3 1 0 3
P1 5 2 3 8
P4 6 3 8 14
P3 8 4 14 22

Average Waiting Time = 6.25


Average Turnaround Time = 11.75
d)Round Robin
#include <stdio.h>
int main()
{
int n, i, time = 0, remain;
int bt[20], rt[20], wt[20], tat[20];
int tq;
float avg_wt = 0, avg_tat = 0;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter burst times:\n");
for(i = 0; i < n; i++)
{
printf("P%d: ", i+1);
scanf("%d", &bt[i]);
rt[i] = bt[i]; // remaining time
}
printf("Enter Time Quantum: ");
scanf("%d", &tq);
remain = n;
while(remain != 0)
{
for(i = 0; i < n; i++)
{
if(rt[i] > 0)
{
if(rt[i] <= tq)
{
time += rt[i];
wt[i] = time - bt[i];
rt[i] = 0;
remain--;
}
else
{
time += tq;
rt[i] -= tq;
}
}
}
}
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++)
{
tat[i] = bt[i] + wt[i];
printf("P%d\t%d\t\t%d\t\t%d\n", i+1, bt[i], wt[i], tat[i]);
avg_wt += wt[i];
avg_tat += tat[i];
}
printf("\nAverage Waiting Time = %.2f", avg_wt/n);
printf("\nAverage Turnaround Time = %.2f\n", avg_tat/n);
return 0;
}
OutPut:
Enter number of processes: 4
Enter burst times:
P1: 5
P2: 4
P3: 2
P4: 1
Enter Time Quantum: 2

Process Burst Time Waiting Time Turnaround Time


P1 5 7 12
P2 4 7 11
P3 2 4 6
P4 1 6 7

Average Waiting Time = 6.00


Average Turnaround Time = 9.00
5. Control the number of ports opened by the operating system with
a) Semaphore
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define MAX_PORTS 2 // OS allows only 2 ports at a time


#define TOTAL_PROCESSES 5

sem_t port_semaphore;

/* Thread simulating a process requesting a port */


void* process(void* arg) {
int pid = *(int*)arg;

printf("Process %d requesting a port...\n", pid);

// Wait if no port is available


sem_wait(&port_semaphore);

// Port allocated
printf("Process %d allocated a port\n", pid);
sleep(2); // Simulate port usage

printf("Process %d releasing the port\n", pid);

// Release port
sem_post(&port_semaphore);

return NULL;
}

int main() {
pthread_t threads[TOTAL_PROCESSES];
int pids[TOTAL_PROCESSES];

// Initialize semaphore with MAX_PORTS


sem_init(&port_semaphore, 0, MAX_PORTS);

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


pids[i] = i + 1;
pthread_create(&threads[i], NULL, process, &pids[i]);
}

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


pthread_join(threads[i], NULL);
}
sem_destroy(&port_semaphore);

return 0;
}
Output:
Process 1 requesting a port...
Process 1 allocated a port
Process 2 requesting a port...
Process 2 allocated a port
Process 3 requesting a port...
Process 4 requesting a port...
Process 5 requesting a port...
Process 2 releasing the port
Process 1 releasing the port
Process 3 allocated a port
Process 4 allocated a port
Process 3 releasing the port
Process 5 allocated a port
Process 4 releasing the port
Process 5 releasing the port
b)Monitors.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define PORTS 2

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
int available = PORTS;

void* process(void* arg) {


int id = *(int*)arg;

pthread_mutex_lock(&m);
while (available == 0)
pthread_cond_wait(&c, &m);

available--;
printf("Process %d got port\n", id);
pthread_mutex_unlock(&m);

sleep(1); // using port

pthread_mutex_lock(&m);
available++;
printf("Process %d released port\n", id);
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);

return NULL;
}

int main() {
pthread_t t[4];
int id[4] = {1,2,3,4};

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


pthread_create(&t[i], NULL, process, &id[i]);

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


pthread_join(t[i], NULL);

return 0;
}
Output:
Process 1 got port
Process 2 got port
Process 1 released port
Process 3 got port
Process 2 released port
Process 4 got port
Process 3 released port
Process 4 released port
6. Write a program to illustrate concurrent execution of threads using pthreads
library.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// Thread function
void* thread_function(void* arg)
{
int thread_id = *(int*)arg;
for (int i = 1; i <= 5; i++)
{
printf("Thread %d is executing iteration %d\n", thread_id, i);
sleep(1); // simulate work
}
pthread_exit(NULL);
}
int main()
{
pthread_t t1, t2;
int id1 = 1, id2 = 2;
// Create threads
pthread_create(&t1, NULL, thread_function, &id1);
pthread_create(&t2, NULL, thread_function, &id2);
// Wait for threads to finish
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Both threads have finished execution.\n");
return 0;
}
Output:
Thread 1 is executing iteration 1
Thread 2 is executing iteration 1
Thread 1 is executing iteration 2
Thread 2 is executing iteration 2
Thread 1 is executing iteration 3
Thread 2 is executing iteration 3
Thread 1 is executing iteration 4
Thread 2 is executing iteration 4
Thread 1 is executing iteration 5
Thread 2 is executing iteration 5
Both threads have finished execution.
7. Write A Program To Solve Producer-consumer problem using Semaphores.
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define BUFFER_SIZE 5

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

// Semaphores
sem_t empty, full, mutex;

// Producer thread
void* producer(void* arg)
{
int item;
for (item = 1; item <= 5; item++)
{
sem_wait(&empty); // wait for empty slot
sem_wait(&mutex); // enter critical section
buffer[in] = item;
printf("Producer produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
sem_post(&mutex); // exit critical section
sem_post(&full); // increment full slots
sleep(1);
}
return NULL;
}

// Consumer thread
void* consumer(void* arg)
{
int item;
for (int i = 1; i <= 5; i++)
{
sem_wait(&full); // wait for item
sem_wait(&mutex); // enter critical section
item = buffer[out];
printf("Consumer consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
sem_post(&mutex); // exit critical section
sem_post(&empty); // increment empty slots
sleep(1);
}
return NULL;
}
int main()
{
pthread_t prod, cons;
// Initialize semaphores
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
// Create threads
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
// Wait for threads
pthread_join(prod, NULL);
pthread_join(cons, NULL);
// Destroy semaphores
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
Output:
Producer produced: 1
Consumer consumed: 1
Producer produced: 2
Consumer consumed: 2
Producer produced: 3
Consumer consumed: 3
Producer produced: 4
Consumer consumed: 4
Producer produced: 5
Consumer consumed: 5
8. Implement the following memory allocation methods for fixed partition
a) First fit
#include <stdio.h>
int main()
{
int m, p, i, j;
int blockSize[10], processSize[10];
int allocation[10];
// Initialize allocation array
for (i = 0; i < 10; i++)
{
allocation[i] = -1;
}
// Input number of memory blocks
printf("Enter number of memory blocks: ");
scanf("%d", &m);
printf("Enter size of each memory block:\n");
for (i = 0; i < m; i++)
{
scanf("%d", &blockSize[i]);
}
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &p);
printf("Enter size of each process:\n");
for (i = 0; i < p; i++)
{
scanf("%d", &processSize[i]);
}
// First Fit Allocation
for (i = 0; i < p; i++)
{
for (j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
allocation[i] = j;
blockSize[j] = 0; // Mark block as allocated
break;
}
}
}
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (i = 0; i < p; 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");
}

return 0;
}
Output:
Enter number of memory blocks: 5
Enter size of each memory block:
100 500 200 300 600
Enter number of processes: 4
Enter size of each process:
212 417 112 426

Process No. Process Size Block No.


1 212 2
2 417 5
3 112 3
4 426 Not Allocated

b)Worst fit
#include <stdio.h>

int main()
{
int m, p, i, j;
int blockSize[10], processSize[10];
int allocation[10];
int worstIndex;
// Initialize allocation array
for (i = 0; i < 10; i++)
{
allocation[i] = -1;
}
// Input number of memory blocks
printf("Enter number of memory blocks: ");
scanf("%d", &m);
printf("Enter size of each memory block:\n");
for (i = 0; i < m; i++)
{
scanf("%d", &blockSize[i]);
}
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &p);
printf("Enter size of each process:\n");
for (i = 0; i < p; i++)
{
scanf("%d", &processSize[i]);
}
// Worst Fit Allocation
for (i = 0; i < p; i++)
{
worstIndex = -1;
for (j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (worstIndex == -1 || blockSize[j] > blockSize[worstIndex])
{
worstIndex = j;
}
}
}

if (worstIndex != -1)
{
allocation[i] = worstIndex;
blockSize[worstIndex] = 0; // Mark block as allocated
}
}

// Output
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (i = 0; i < p; 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");
}

return 0;
}
Output:
Enter number of memory blocks: 5
Enter size of each memory block:
100
500
200
300
600
Enter number of processes: 4
Enter size of each process:
212
417
112
426

Process No. Process Size Block No.


1 212 5
2 417 2
3 112 4
4 426 Not Allocated

c)Bestfit
#include <stdio.h>
int main()
{
int m, p, i, j;
int blockSize[10], processSize[10];
int allocation[10];
int bestIndex;
// Initialize allocation array
for (i = 0; i < 10; i++)
{
allocation[i] = -1;
}
// Input number of memory blocks
printf("Enter number of memory blocks: ");
scanf("%d", &m);
printf("Enter size of each memory block:\n");
for (i = 0; i < m; i++)
{
scanf("%d", &blockSize[i]);
}
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &p);
printf("Enter size of each process:\n");
for (i = 0; i < p; i++)
{
scanf("%d", &processSize[i]);
}
// Best Fit Allocation
for (i = 0; i < p; i++)
{
bestIndex = -1;
for (j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIndex == -1 || blockSize[j] < blockSize[bestIndex])
{
bestIndex = j;
}
}
}
if (bestIndex != -1)
{
allocation[i] = bestIndex;
blockSize[bestIndex] = 0; // Mark block as allocated
}
}
// Output
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (i = 0; i < p; 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");
}
return 0;
}
Output:
Enter number of memory blocks: 5
Enter size of each memory block:
100
500
200
300
600
Enter number of processes: 4
Enter size of each process:
212
417
112
426

Process No. Process Size Block No.


1 212 4
2 417 2
3 112 3
4 426 5
9. Simulate the following page replacement algorithms
a) FIFO b)LRU c)LFU
a) FIFO
#include <stdio.h>
int main()
{
int frames[10], pages[50];
int n, f, i, j, k, flag, pageFaults = 0;
int index = 0; // Points to the oldest page (FIFO)
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter reference string: ");
for(i = 0; i < n; i++)
{
scanf("%d", &pages[i]);
}
printf("Enter number of frames: ");
scanf("%d", &f);
// Initialize frames with -1 (empty)
for(i = 0; i < f; i++)
{
frames[i] = -1;
}
printf("\nPage\tFrames\n");
for(i = 0; i < n; i++)
{
flag = 0;
// Check if page is already in frame (Hit)
for(j = 0; j < f; j++)
{
if(frames[j] == pages[i])
{
flag = 1;
break;
}
}
// If page not found (Page Fault)
if(flag == 0)
{
frames[index] = pages[i]; // Replace oldest page
index = (index + 1) % f; // Move FIFO pointer
pageFaults++;
}
// Print current frame status
printf("%d\t", pages[i]);
for(k = 0; k < f; k++)
{
if(frames[k] != -1)
printf("%d ", frames[k]);
else
printf("- ");
}
printf("\n");
}
printf("\nTotal Page Faults = %d\n", pageFaults);
return 0;
}
OutPut:
Enter number of pages: 12
Enter reference string: 1
2
3
4
1
2
5
1
2
3
4
5
Enter number of frames: 3
Page Frames
1 1 - -
2 1 2 -
3 1 2 3
4 4 2 3
1 4 1 3
2 4 1 2
5 5 1 2
1 5 1 2
2 5 1 2
3 5 3 2
4 5 3 4
5 5 3 4
Total Page Faults = 9
b)LRU
#include <stdio.h>
int main()
{
int pages[50], frames[10], time[10];
int n, f, i, j, pos, least, pageFaults = 0, counter = 0, flag;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter reference string: ");
for(i = 0; i < n; i++)
scanf("%d", &pages[i]);
printf("Enter number of frames: ");
scanf("%d", &f);
for(i = 0; i < f; i++)
frames[i] = -1;
printf("\nPage\tFrames\n");
for(i = 0; i < n; i++)
{
flag = 0;
// Check for page hit
for(j = 0; j < f; j++)
{
if(frames[j] == pages[i])
{
counter++;
time[j] = counter;
flag = 1;
break;
}
}
// If page fault
if(flag == 0)
{
least = 0;
for(j = 1; j < f; j++)
if(time[j] < time[least])
least = j;
frames[least] = pages[i];
counter++;
time[least] = counter;
pageFaults++;
}
// Display frames
printf("%d\t", pages[i]);
for(j = 0; j < f; j++)
{
if(frames[j] != -1)
printf("%d ", frames[j]);
else
printf("- ");
}
printf("\n");
}
printf("\nTotal Page Faults = %d\n", pageFaults);
return 0;
}
OutPut:
Enter number of pages: 12
Enter reference string: 1
2
3
4
1
2
5
1
2

4
5
3
Enter number of frames: 3

Page Frames
1 1 - -
2 1 2 -
3 1 2 3
4 4 2 3
1 4 1 3
2 4 1 2
5 5 1 2
1 5 1 2
2 5 1 2
4 4 1 2
5 4 5 2
3 4 5 3

Total Page Faults = 10


c)LFU
#include <stdio.h>
int main()
{
int pages[50], frames[10], freq[10], time[10];
int n, f, i, j, pos, min, pageFaults = 0, counter = 0;
int flag;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter reference string: ");
for(i = 0; i < n; i++)
scanf("%d", &pages[i]);
printf("Enter number of frames: ");
scanf("%d", &f);
for(i = 0; i < f; i++)
{
frames[i] = -1;
freq[i] = 0;
}
printf("\nPage\tFrames\n");
for(i = 0; i < n; i++)
{
flag = 0;
// Check for hit
for(j = 0; j < f; j++)
{
if(frames[j] == pages[i])
{
freq[j]++;
flag = 1;
break;
}
}
// If page fault
if(flag == 0)
{
min = 0;
for(j = 1; j < f; j++)
{
if(freq[j] < freq[min])
min = j;
}
frames[min] = pages[i];
freq[min] = 1;
pageFaults++;
}
printf("%d\t", pages[i]);
for(j = 0; j < f; j++)
{
if(frames[j] != -1)
printf("%d ", frames[j]);
else
printf("- ");
}
printf("\n");
}
printf("\nTotal Page Faults = %d\n", pageFaults);
return 0;
}
OutPut:
Enter number of pages: 12
Enter reference string: 1
2
3
4
1
2
5
1
2
3
4
5
Enter number of frames: 3

Page Frames
1 1 - -
2 1 2 -
3 1 2 3
4 4 2 3
1 1 2 3
2 1 2 3
5 5 2 3
1 1 2 3
2 1 2 3
3 1 2 3
4 4 2 3
5 5 2 3

Total Page Faults = 9


Note: The output may slightly vary depending on: Tie-breaking rule (FIFO or LRU when
frequency is equal)
10. Simulate Paging Technique of memory management.
#include <stdio.h>
int main()
{
int pageTable[50];
int n, pageSize;
int logicalAddress, pageNumber, offset;
int frameNumber, physicalAddress;
int i;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter page size: ");
scanf("%d", &pageSize);
printf("\nEnter frame number for each page:\n");
for(i = 0; i < n; i++)
{
printf("Page %d -> Frame: ", i);
scanf("%d", &pageTable[i]);
}
printf("\nEnter logical address: ");
scanf("%d", &logicalAddress);
// Calculate page number and offset
pageNumber = logicalAddress / pageSize;
offset = logicalAddress % pageSize;
if(pageNumber >= n)
{
printf("\nInvalid Logical Address! Page does not exist.\n");
}
else
{
frameNumber = pageTable[pageNumber];
physicalAddress = (frameNumber * pageSize) + offset;
printf("\nPage Number = %d\n", pageNumber);
printf("Offset = %d\n", offset);
printf("Frame Number = %d\n", frameNumber);
printf("Physical Address = %d\n", physicalAddress);
}
return 0;
}
OutPut:
Enter number of pages: 4
Enter page size: 1024
Enter frame number for each page:
Page 0 -> Frame: 5
Page 1 -> Frame: 2
Page 2 -> Frame: 7
Page 3 -> Frame: 1
Enter logical address: 2050
Page Number = 2
Offset = 2
Frame Number = 7
Physical Address = 7170
11. Implement Bankers Algorithm for DeadLock avoidance and prevention
#include <stdio.h>
int main()
{
int n, m;
int i, j, k;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter number of resource types: ");
scanf("%d", &m);
int alloc[10][10], max[10][10], need[10][10];
int avail[10], finish[10] = {0}, safe[10];
printf("Enter Allocation Matrix:\n");
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
scanf("%d", &alloc[i][j]);
printf("Enter Maximum Matrix:\n");
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
scanf("%d", &max[i][j]);
printf("Enter Available Resources:\n");
for(i = 0; i < m; i++)
scanf("%d", &avail[i]);
// Calculate Need = Max - Allocation
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
int count = 0;
while(count < n)
{
int found = 0;
for(i = 0; i < n; i++)
{
if(finish[i] == 0)
{
int possible = 1;
for(j = 0; j < m; j++)
{
if(need[i][j] > avail[j])
{
possible = 0;
break;
}
}
if(possible)
{
for(k = 0; k < m; k++)
avail[k] += alloc[i][k];
safe[count++] = i;
finish[i] = 1;
found = 1;
}
}
}
if(!found)
{
printf("\nSystem is NOT Safe.\n");
return 0;
}
}
printf("\nSystem is Safe.\nSafe Sequence: ");
for(i = 0; i < n; i++)
printf("P%d ", safe[i]);
return 0;
}
Output:
Enter number of processes: 5
Enter number of resource types: 3
Enter Allocation Matrix:
010
200
302
211
002
Enter Maximum Matrix:
753
322
902
222
433
Enter Available Resources:
332
System is Safe.
Safe Sequence: P1 P3 P4 P0 P2
12. Simulate the following file allocation strategies
a) Sequential b)Indexed c)Linked
a) Sequential
#include <stdio.h>
int main()
{
int totalBlocks, fileSize;
int startBlock;
int disk[50] = {0};
int i;
printf("Enter total number of disk blocks: ");
scanf("%d", &totalBlocks);
printf("Enter starting block for file: ");
scanf("%d", &startBlock);
printf("Enter file size (number of blocks): ");
scanf("%d", &fileSize);
// Check if enough space exists
if(startBlock + fileSize > totalBlocks)
{
printf("\nAllocation not possible (Out of bounds).\n");
return 0;
}
// Check if blocks are free
for(i = startBlock; i < startBlock + fileSize; i++)
{
if(disk[i] == 1)
{
printf("\nBlock %d already allocated. Allocation failed.\n", i);
return 0;
}
}
// Allocate blocks
for(i = startBlock; i < startBlock + fileSize; i++)
{
disk[i] = 1;
}
printf("\nFile allocated successfully.\nAllocated blocks:\n");
for(i = startBlock; i < startBlock + fileSize; i++)
{
printf("Block %d\n", i);
}
return 0;
}
Output:
Enter total number of disk blocks: 10
Enter starting block for file: 3
Enter file size (number of blocks): 4

File allocated successfully.


Allocated blocks:
Block 3
Block 4
Block 5
Block 6
b)Indexed
#include <stdio.h>
int main()
{
int totalBlocks, fileSize;
int indexBlock;
int disk[50] = {0};
int block[50];
int i;
printf("Enter total number of disk blocks: ");
scanf("%d", &totalBlocks);
printf("Enter index block: ");
scanf("%d", &indexBlock);
if(disk[indexBlock] == 1)
{
printf("\nIndex block already allocated.\n");
return 0;
}
printf("Enter number of blocks needed for file: ");
scanf("%d", &fileSize);
printf("Enter block numbers for file:\n");
for(i = 0; i < fileSize; i++)
{
scanf("%d", &block[i]);
if(disk[block[i]] == 1)
{
printf("\nBlock %d already allocated. Allocation failed.\n", block[i]);
return 0;
}
}
// Allocate index block
disk[indexBlock] = 1;
// Allocate file blocks
for(i = 0; i < fileSize; i++)
disk[block[i]] = 1;
printf("\nFile allocated successfully.\n");
printf("Index Block: %d\n", indexBlock);
printf("Allocated Blocks: ");
for(i = 0; i < fileSize; i++)
printf("%d ", block[i]);
return 0;
}
OutPut:
Enter total number of disk blocks: 10
Enter index block: 2
Enter number of blocks needed for file: 3
Enter block numbers for file:
478

File allocated successfully.


Index Block: 2
Allocated Blocks: 4 7 8
c)Linked
#include <stdio.h>
int main()
{
int totalBlocks, fileSize;
int disk[50] = {0};
int blocks[50];
int i;
printf("Enter total number of disk blocks: ");
scanf("%d", &totalBlocks);
printf("Enter number of blocks needed for file: ");
scanf("%d", &fileSize);
printf("Enter block numbers for file:\n");
for(i = 0; i < fileSize; i++)
{
scanf("%d", &blocks[i]);
if(disk[blocks[i]] == 1)
{
printf("\nBlock %d already allocated. Allocation failed.\n", blocks[i]);
return 0;
}
}
// Allocate blocks
for(i = 0; i < fileSize; i++)
disk[blocks[i]] = 1;
printf("\nFile allocated successfully.\n");
printf("Linked Allocation (Block -> Next Block):\n");
for(i = 0; i < fileSize - 1; i++)
{
printf("%d -> %d\n", blocks[i], blocks[i+1]);
}
printf("%d -> NULL\n", blocks[fileSize - 1]);
return 0;
}
OutPut:
Enter total number of disk blocks: 10
Enter number of blocks needed for file: 4
Enter block numbers for file:
3719
File allocated successfully.
Linked Allocation (Block -> Next Block):
3 -> 7
7 -> 1
1 -> 9
9 -> NULL
simulate disk scheduling algorithm
a) SSTF
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
int n, i, j;

printf("Enter number of requests: ");


scanf("%d", &n);

int request[n];
int visited[n];

printf("Enter the request sequence:\n");


for(i = 0; i < n; i++) {
scanf("%d", &request[i]);
visited[i] = 0; // Mark all requests as unvisited
}

int head;
printf("Enter initial head position: ");
scanf("%d", &head);

int total_seek_time = 0;
int current = head;

printf("\nSeek Sequence: %d", current);

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


int min = 9999;
int index = -1;

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


if(!visited[j]) {
int distance = abs(current - request[j]);
if(distance < min) {
min = distance;
index = j;
}
}
}

visited[index] = 1;
total_seek_time += abs(current - request[index]);
current = request[index];

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


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

return 0;
}
OutPut:
Enter number of requests: 8
Enter the request sequence:
98 183 37 122 14 124 65 67
Enter initial head position: 53

Seek Sequence: 53 -> 65 -> 67 -> 37 -> 14 -> 98 -> 122 -> 124 -> 183

Total Seek Time: 236


B) SCAN
#include <stdio.h>
#include <stdlib.h>

void sort(int arr[], int n) {


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

int main() {
int n, head, size, direction;

printf("Enter number of requests: ");


scanf("%d", &n);

int request[n];

printf("Enter request sequence:\n");


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

printf("Enter initial head position: ");


scanf("%d", &head);

printf("Enter total disk size (max cylinder number): ");


scanf("%d", &size);
printf("Enter direction (0 = left, 1 = right): ");
scanf("%d", &direction);

sort(request, n);

int total_seek = 0;
int current = head;

printf("\nSeek Sequence: %d", current);

if(direction == 1) { // Moving Right


for(int i = 0; i < n; i++) {
if(request[i] >= head) {
total_seek += abs(current - request[i]);
current = request[i];
printf(" -> %d", current);
}
}

// Move to end
total_seek += abs(current - (size - 1));
current = size - 1;
printf(" -> %d", current);

for(int i = n - 1; i >= 0; i--) {


if(request[i] < head) {
total_seek += abs(current - request[i]);
current = request[i];
printf(" -> %d", current);
}
}
}
else { // Moving Left
for(int i = n - 1; i >= 0; i--) {
if(request[i] <= head) {
total_seek += abs(current - request[i]);
current = request[i];
printf(" -> %d", current);
}
}

// Move to beginning
total_seek += abs(current - 0);
current = 0;
printf(" -> %d", current);

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


if(request[i] > head) {
total_seek += abs(current - request[i]);
current = request[i];
printf(" -> %d", current);
}
}
}

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

return 0;
}
OutPut:
Enter number of requests: 8
Enter request sequence:
98 183 37 122 14 124 65 67
Enter initial head position: 53
Enter total disk size (max cylinder number): 200
Enter direction (0 = left, 1 = right): 1

Seek Sequence: 53 -> 65 -> 67 -> 98 -> 122 -> 124 -> 183 -> 199 -> 37 -> 14

Total Seek Time: 331

Q) C Program for implementation of system calls


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

int main() {
int fd;
char buffer[50];
pid_t pid;

pid = fork(); // Create child process


if(pid == 0) { // Child process
printf("Child Process ID: %d\n", getpid());

fd = open("[Link]", O_CREAT | O_RDWR, 0644);


write(fd, "Hello OS Lab\n", 13);

lseek(fd, 0, SEEK_SET);
read(fd, buffer, 13);

printf("Child Read: %s", buffer);


close(fd);
}
else { // Parent process
wait(NULL); // Wait for child
printf("Parent Process ID: %d\n", getpid());
}

return 0;
}
OutPut:
Child Process ID: 2924
Child Read: Parent Process ID: 2923

Q) Simulate Dinning Philosopher Problem


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define N 5 // Number of philosophers

pthread_mutex_t chopstick[N];
sem_t room; // To avoid deadlock (only 4 philosophers allowed at a time)

void* philosopher(void* num) {


int id = *(int*)num;

while(1) {
printf("Philosopher %d is Thinking\n", id);
sleep(1);

sem_wait(&room); // Enter room

pthread_mutex_lock(&chopstick[id]); // Pick left


pthread_mutex_lock(&chopstick[(id+1)%N]); // Pick right

printf("Philosopher %d is Eating\n", id);


sleep(1);
pthread_mutex_unlock(&chopstick[id]); // Release left
pthread_mutex_unlock(&chopstick[(id+1)%N]); // Release right

sem_post(&room); // Leave room


}
}

int main() {
pthread_t ph[N];
int id[N];

sem_init(&room, 0, N-1); // Allow only 4 philosophers

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


pthread_mutex_init(&chopstick[i], NULL);

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


id[i] = i;
pthread_create(&ph[i], NULL, philosopher, &id[i]);
}

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


pthread_join(ph[i], NULL);

return 0;
}
OutPut:
Philosopher 0 is Thinking
Philosopher 1 is Thinking
Philosopher 2 is Thinking
Philosopher 3 is Thinking
Philosopher 4 is Thinking
Philosopher 0 is Eating
Philosopher 2 is Eating
Philosopher 2 is Thinking….

You might also like