0% found this document useful (0 votes)
3 views29 pages

Operating System Lab File

The document contains multiple C programs demonstrating various system calls and scheduling algorithms in UNIX and Windows environments. It includes implementations for process management using fork, exec, and wait, file operations with open and read, and process scheduling algorithms like FCFS, SJF, Round Robin, and Priority Scheduling. Additionally, it showcases inter-process communication using pipes.

Uploaded by

ankit362541
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)
3 views29 pages

Operating System Lab File

The document contains multiple C programs demonstrating various system calls and scheduling algorithms in UNIX and Windows environments. It includes implementations for process management using fork, exec, and wait, file operations with open and read, and process scheduling algorithms like FCFS, SJF, Round Robin, and Priority Scheduling. Additionally, it showcases inter-process communication using pipes.

Uploaded by

ankit362541
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

PROGRAM-1

Write programs using the following system calls of UNIX operating system: fork, exec,
getpid, exit, wait, stat, opendir, readdir.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <direct.h>
int main() {
STARTUPINFO si;
PROCESS_INFORMATION pi;
struct _stat fileStat;
WIN32_FIND_DATA findFileData;
HANDLE hFind;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Simulate getpid()
DWORD pid = GetCurrentProcessId();
printf("Parent process ID: %lu\n", pid);
// Simulate fork + exec: create a new process running "cmd /C dir"
if (!CreateProcess(
NULL,
"cmd.exe /C dir", // Simulate exec("ls -l")
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi)
){
printf("CreateProcess failed (%lu).\n", GetLastError());
return 1;
}
// Simulate wait()
WaitForSingleObject(pi.hProcess, INFINITE);
printf("Child process finished.\n");
// Close process/thread handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
// Simulate stat() on "testfile.txt"
if (_stat("testfile.txt", &fileStat) == 0) {
printf("\nFile Information (testfile.txt):\n");
printf("Size: %ld bytes\n", fileStat.st_size);
printf("Modified time: %ld\n", fileStat.st_mtime);
} else {
perror("stat failed (file 'testfile.txt' may not exist)");
}
// Simulate opendir() + readdir()
printf("\nCurrent Directory Contents:\n");
hFind = FindFirstFile("*", &findFileData);
if (hFind == INVALID_HANDLE_VALUE) {
printf("FindFirstFile failed (%lu)\n", GetLastError());
return 1;
} else {
do {
printf("%s\n", findFileData.cFileName);
} while (FindNextFile(hFind, &findFileData));
FindClose(hFind);
}

// Simulate exit()
exit(0);
}
PROGRAM-2
Write programs using the I/O system calls of UNIX operating system (open, read, write, etc)
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <unistd.h>

#define BUFFER_SIZE 1024


int main() {
int inputFd, outputFd;
char buffer[BUFFER_SIZE];
ssize_t bytesRead, bytesWritten;
// Open the input file (read-only)
inputFd = open("input.txt", O_RDONLY);
if (inputFd < 0) {
perror("Error opening input.txt");
return 1;
}
// Open/create the output file (write-only)
outputFd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (outputFd < 0) {
perror("Error opening output.txt");
close(inputFd);
return 1;
}
// Read from input and write to output
while ((bytesRead = read(inputFd, buffer, BUFFER_SIZE)) > 0) {
bytesWritten = write(outputFd, buffer, bytesRead);
if (bytesWritten != bytesRead) {
perror("Write error");
close(inputFd);
close(outputFd);
return 1
}
}
if (bytesRead < 0) {
perror("Read error");
} else {
printf("File copied successfully using system calls.\n");
}
// Close files
close(inputFd);
close(outputFd);
return 0;
}
PROGRAM-3
Write C programs to simulate UNIX commands like ls, grep, etc.
// (LS command)
#include <stdio.h>
#include <windows.h>
int main() {
WIN32_FIND_DATA findFileData;
HANDLE hFind;
hFind = FindFirstFile("*", &findFileData);
if (hFind == INVALID_HANDLE_VALUE) {
printf("No files found.\n");
return 1;
}
printf("Directory contents:\n");
do {
printf("%s\n", findFileData.cFileName);
} while (FindNextFile(hFind, &findFileData) != 0);
FindClose(hFind);

return 0;
}
//grep Command
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 1024


int main() {
char filename[100], keyword[100], line[MAX_LINE];
FILE *fp;
printf("Enter filename: ");
scanf("%s", filename);
printf("Enter keyword to search: ");
scanf("%s", keyword);
fp = fopen(filename, "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
printf("Lines containing \"%s\":\n", keyword);
while (fgets(line, sizeof(line), fp)) {
if (strstr(line, keyword)) {
printf("%s", line);
}
}
fclose(fp);
return 0;
}
PROGRAM-4
Given the list of processes, their CPU burst times and arrival times, display/print the
Gantt chart for FCFS and SJF. For each of the scheduling policies, compute and print
the average waiting time and average turnaround time (2 sessions)

//FCFS
#include <stdio.h>
int main()
{
int n, i,j;
printf("Enter number of processes: ");
scanf("%d", &n);
int pid[n], arrival_time[n], burst_time[n];
int waiting_time[n], turnaround_time[n], completion_time[n];
float total_wt = 0, total_tat = 0;
// Input process details
printf("Enter Process ID, Arrival Time, and Burst Time:\n");
for (i = 0; i < n; i++)
{
scanf("%d %d %d", &pid[i], &arrival_time[i], &burst_time[i]);
}
// Sorting processes by arrival time (Bubble Sort)
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++) {
if (arrival_time[j] > arrival_time[j + 1]) {
// Swap arrival time
int temp = arrival_time[j];
arrival_time[j] = arrival_time[j + 1];
arrival_time[j + 1] = temp;
// Swap burst time
temp = burst_time[j];
burst_time[j] = burst_time[j + 1];
burst_time[j + 1] = temp;
// Swap process ID
temp = pid[j];
pid[j] = pid[j + 1];
pid[j + 1] = temp;
}
}
}
int time = 0;
printf("\nFCFS Gantt Chart:\n");
for (i = 0; i < n; i++) {
if (time < arrival_time[i]) {
time = arrival_time[i]; // If CPU is idle, move time to process arrival time
}
printf("| P%d ", pid[i]);
completion_time[i] = time + burst_time[i]; // Completion time
turnaround_time[i] = completion_time[i] - arrival_time[i]; // Turnaround time
waiting_time[i] = turnaround_time[i] - burst_time[i]; // Waiting time
total_wt += waiting_time[i];
total_tat += turnaround_time[i];
time = completion_time[i]; // Update time
}
printf("|\n");
// Print table
printf("\nProcess\tArrival\tBurst\tWaiting\tTurnaround\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t%d\t%d\t%d\n", pid[i], arrival_time[i], burst_time[i], waiting_time[i],
turnaround_time[i]);
}// Print averages
printf("\nAverage Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
return 0;}
//SJF
#include <stdio.h>
int main()
{
int n, i, j, temp;
printf("Enter number of processes: ");
scanf("%d", &n);
int pid[n], arrival_time[n], burst_time[n];
int waiting_time[n], turnaround_time[n], completion_time[n];
float total_wt = 0, total_tat = 0;
// Input process details
printf("Enter Process ID, Arrival Time, and Burst Time:\n");
for (i = 0; i < n; i++) {
scanf("%d %d %d", &pid[i], &arrival_time[i], &burst_time[i]);
}
// Sorting based on arrival time and burst time (SJF Logic)
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++)
{
if ((arrival_time[i] > arrival_time[j]) ||
(arrival_time[i] == arrival_time[j] && burst_time[i] > burst_time[j]))
{
// Swap arrival time
temp = arrival_time[i];
arrival_time[i] = arrival_time[j];
arrival_time[j] = temp;
// Swap burst time
temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;

// Swap process ID
temp = pid[i];
pid[i] = pid[j];
pid[j] = temp;
}
}
}
int time = 0;
printf("\nSJF Gantt Chart:\n");
for (i = 0; i < n; i++) {
if (time < arrival_time[i]) {
time = arrival_time[i]; // If CPU is idle, move time to process arrival time
}
printf("| P%d ", pid[i]);
completion_time[i] = time + burst_time[i]; // Completion time
turnaround_time[i] = completion_time[i] - arrival_time[i]; // Turnaround time
waiting_time[i] = turnaround_time[i] - burst_time[i]; // Waiting time
total_wt += waiting_time[i];
total_tat += turnaround_time[i];
time = completion_time[i]; // Update time
}
printf("|\n");
// Print table
printf("\nProcess\tArrival\tBurst\tWaiting\tTurnaround\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t%d\t%d\t%d\n", pid[i], arrival_time[i], burst_time[i], waiting_time[i],
turnaround_time[i]);
}
// Print averages
printf("\nAverage Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
return 0;
}
PROGRAM-5
Given the list of processes, their CPU burst times, and arrival times, display or print the
Gantt chart for both Priority and Round Robin scheduling. For each scheduling policy,
compute and print the average waiting and turnaround times for two sessions.

//Round Robin
#include <stdio.h>
int main() {
int n, time_quantum,i;
printf("Enter number of processes: ");
scanf("%d", &n);
int arrival_time[n], burst_time[n], remaining_time[n];
// Input for arrival time and burst time
for (i = 0; i < n; i++)
{
printf("Enter arrival time and burst time for process %d: ", i + 1);
scanf("%d %d", &arrival_time[i], &burst_time[i]);
remaining_time[i] = burst_time[i];
}
printf("Enter time quantum: ");
scanf("%d", &time_quantum);
int time = 0, completed = 0;
int total_waiting_time = 0, total_turnaround_time = 0;
printf("\nGantt Chart:\n");
while (completed < n) {
int executed = 0;
for (i = 0; i < n; i++)
{
if (arrival_time[i] <= time && remaining_time[i] > 0) {
printf("| P%d ", i + 1);
if (remaining_time[i] <= time_quantum) {
time += remaining_time[i];
remaining_time[i] = 0;
completed++;
int turnaround_time = time - arrival_time[i];
int waiting_time = turnaround_time - burst_time[i];
total_turnaround_time += turnaround_time;
total_waiting_time += waiting_time;
}
else
{
remaining_time[i] -= time_quantum;
time += time_quantum;
}
executed = 1;
}
}
if (!executed) {
printf("| IDLE ");
time++;
}
}
printf("|\n");
float avg_waiting_time = (float)total_waiting_time / n;
float avg_turnaround_time = (float)total_turnaround_time / n;
printf("\nAverage Turnaround Time: %.2f\n", avg_turnaround_time);
printf("Average Waiting Time: %.2f\n", avg_waiting_time);
return 0;
}
//Priority Scheduling
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter number of processes: ");
scanf("%d", &n);
int pid[n], arrival_time[n], burst_time[n], priority[n];
int waiting_time[n], turnaround_time[n], completion_time[n];
float total_wt = 0, total_tat = 0;
// Input process details
printf("Enter Process ID, Arrival Time, Burst Time, and Priority:\n");
for (i = 0; i < n; i++) {
scanf("%d %d %d %d", &pid[i], &arrival_time[i], &burst_time[i], &priority[i]);
}
// Sorting based on priority (lower number = higher priority)
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if ((priority[i] > priority[j]) ||
(priority[i] == priority[j] && arrival_time[i] > arrival_time[j])) {
// Swap priority
temp = priority[i];
priority[i] = priority[j];
priority[j] = temp;
// Swap arrival time
temp = arrival_time[i];
arrival_time[i] = arrival_time[j];
arrival_time[j] = temp;
// Swap burst time
temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;
// Swap process ID
temp = pid[i];
pid[i] = pid[j];
pid[j] = temp;
}
}
}
int time = 0;
printf("\nPriority Scheduling Gantt Chart:\n");
for (i = 0; i < n; i++) {
if (time < arrival_time[i]) {
time = arrival_time[i]; // If CPU is idle, move time to process arrival time
}
printf("| P%d ", pid[i]);
completion_time[i] = time + burst_time[i]; // Completion time
turnaround_time[i] = completion_time[i] - arrival_time[i]; // Turnaround time
waiting_time[i] = turnaround_time[i] - burst_time[i]; // Waiting time
total_wt += waiting_time[i];
total_tat += turnaround_time[i];
time = completion_time[i]; // Update time
}
printf("|\n");
// Print table
printf("\nProcess\tArrival\tBurst\tPriority\tWaiting\tTurnaround\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t%d\t%d\t%d\t%d\n", pid[i], arrival_time[i], burst_time[i], priority[i],
waiting_time[i], turnaround_time[i]);
}
// Print averages
printf("\nAverage Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
return 0;
}
PROGRAM-6
Developing Applications using Inter Process communication (using shared memory and
pipes)
// pipe_server
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hPipe;
char buffer[] = "Hello from server through pipe!";
DWORD bytesWritten;

hPipe = CreateNamedPipe(
TEXT("\\\\.\\pipe\\MyPipe"),
PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_BYTE | PIPE_WAIT,
1, 1024, 1024, 0, NULL);
if (hPipe == INVALID_HANDLE_VALUE) {
printf("Failed to create pipe. Error: %lu\n", GetLastError());
return 1;
}
printf("Waiting for client to connect...\n");
ConnectNamedPipe(hPipe, NULL);
WriteFile(hPipe, buffer, sizeof(buffer), &bytesWritten, NULL);
printf("Sent message: %s\n", buffer);
CloseHandle(hPipe);
return 0;
}

// Client
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hPipe;
char buffer[128];
DWORD bytesRead;
hPipe = CreateFile(
TEXT("\\\\.\\pipe\\MyPipe"),
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe == INVALID_HANDLE_VALUE) {
printf("Failed to connect to pipe. Error: %lu\n", GetLastError());
return 1;
}
ReadFile(hPipe, buffer, sizeof(buffer), &bytesRead, NULL);
printf("Received from server: %s\n", buffer);
CloseHandle(hPipe);
return 0;
}
PROGRAM-7
Simulate the Producer-Consumer problem using semaphores (using UNIX system calls).
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define BUFFER_SIZE 5
#define NUM_ITEMS 10
int buffer[BUFFER_SIZE];
int in = 0, out = 0,i;
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
void *producer(void *arg)
{
for (i = 0; i < NUM_ITEMS; i++) {
int item = i + 1;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
// Produce item
buffer[in] = item;
printf("Producer produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}
void *consumer(void *arg) {
for (i = 0; i < NUM_ITEMS; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
// Consume item
int item = buffer[out];
printf("Consumer consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t prod, cons;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
PROGRAM-8
Write a C program to simulate First fit, best fit, and Worst fit memory management algorithms.

#include <stdio.h>
#define MAX_BLOCKS 10
#define MAX_PROCESSES 10

void firstFit(int blockSize[], int blocks, int processSize[], int processes);


void bestFit(int blockSize[], int blocks, int processSize[], int processes);
void worstFit(int blockSize[], int blocks, int processSize[], int processes);
int main() {
int blockSize[MAX_BLOCKS] = {100, 500, 200, 300, 600};
int processSize[MAX_PROCESSES] = {212, 417, 112, 426};
int blocks = 5, processes = 4;
printf("=== First Fit ===\n");
firstFit(blockSize, blocks, processSize, processes);
printf("\n=== Best Fit ===\n");
bestFit(blockSize, blocks, processSize, processes);
printf("\n=== Worst Fit ===\n");
worstFit(blockSize, blocks, processSize, processes);
return 0;
}
//First fit
void firstFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX_PROCESSES];
int i, j;
for (i = 0; i < processes; i++)
allocation[i] = -1;
int tempBlock[MAX_BLOCKS];
for (i = 0; i < blocks; i++)
tempBlock[i] = blockSize[i];
for (i = 0; i < processes; i++) {
for (j = 0; j < blocks; j++) {
if (tempBlock[j] >= processSize[i]) {
allocation[i] = j;
tempBlock[j] -= processSize[i];
break;
}
}
}
for (i = 0; i < processes; i++) {
printf("Process %d (%d KB) -> ", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}
//Best fit
void bestFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX_PROCESSES];
int i, j;
for (i = 0; i < processes; i++)
allocation[i] = -1;
int tempBlock[MAX_BLOCKS];
for (i = 0; i < blocks; i++)
tempBlock[i] = blockSize[i];
for (i = 0; i < processes; i++) {
int bestIdx = -1;
for (j = 0; j < blocks; j++) {
if (tempBlock[j] >= processSize[i]) {
if (bestIdx == -1 || tempBlock[j] < tempBlock[bestIdx])
bestIdx = j;
}
}
if (bestIdx != -1) {
allocation[i] = bestIdx;
tempBlock[bestIdx] -= processSize[i];
}
}
for (i = 0; i < processes; i++) {
printf("Process %d (%d KB) -> ", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}
//Worst fit
void worstFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX_PROCESSES];
int i, j;
for (i = 0; i < processes; i++)
allocation[i] = -1;
int tempBlock[MAX_BLOCKS];
for (i = 0; i < blocks; i++)
tempBlock[i] = blockSize[i];
for (i = 0; i < processes; i++) {
int worstIdx = -1;
for (j = 0; j < blocks; j++) {
if (tempBlock[j] >= processSize[i]) {
if (worstIdx == -1 || tempBlock[j] > tempBlock[worstIdx])
worstIdx = j;
}
}
if (worstIdx != -1) {
allocation[i] = worstIdx;
tempBlock[worstIdx] -= processSize[i];
}
}
for (i = 0; i < processes; i++) {
printf("Process %d (%d KB) -> ", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}
PROGRAM-9
Write a C program to Simulate Page Replacement Algorithms (FIFO, LRU and
Optimal)

#include <stdio.h>
#define MAX_REF 100
#define MAX_FRAMES 10
void simulateFIFO(int pages[], int n, int frames);
void simulateLRU(int pages[], int n, int frames);
void simulateOptimal(int pages[], int n, int frames);
int main() {
int pages[MAX_REF] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = 13;
int frames = 3;
printf("=== FIFO Page Replacement ===\n");
simulateFIFO(pages, n, frames);
printf("\n=== LRU Page Replacement ===\n");
simulateLRU(pages, n, frames);
printf("\n=== Optimal Page Replacement ===\n");
simulateOptimal(pages, n, frames);
return 0;
}
//FIFO
void simulateFIFO(int pages[], int n, int frames) {
int frame[MAX_FRAMES];
int i, j, k, pageFaults = 0, pointer = 0;
int found;
for (i = 0; i < frames; i++) frame[i] = -1;
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < frames; j++) {
if (frame[j] == pages[i]) {
found = 1;
break;
}
}
if (!found) {
frame[pointer] = pages[i];
pointer = (pointer + 1) % frames;
pageFaults++;
}
printf("Step %2d: ", i + 1);
for (k = 0; k < frames; k++) {
if (frame[k] != -1)
printf("%d ", frame[k]);
else
printf("- ");
}
printf("\n");
}
printf("Total Page Faults (FIFO): %d\n", pageFaults);
}
//LRU
void simulateLRU(int pages[], int n, int frames) {
int frame[MAX_FRAMES], used[MAX_FRAMES];
int i, j, k, pageFaults = 0, time = 0, least;
int found;
for (i = 0; i < frames; i++) {
frame[i] = -1;
used[i] = 0;
}
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < frames; j++) {
if (frame[j] == pages[i]) {
used[j] = time++;
found = 1;
break;
}
}
if (!found) {
int min = used[0];
least = 0;
for (j = 1; j < frames; j++) {
if (used[j] < min) {
min = used[j];
least = j;
}
}
frame[least] = pages[i];
used[least] = time++;
pageFaults++;
}
printf("Step %2d: ", i + 1);
for (k = 0; k < frames; k++) {
if (frame[k] != -1)
printf("%d ", frame[k]);
else
printf("- ");
}
printf("\n");
}
printf("Total Page Faults (LRU): %d\n", pageFaults);
}
int predict(int pages[], int frame[], int n, int index, int frames) {
int i, j, farthest = index, res = -1;
for (i = 0; i < frames; i++) {
for (j = index; j < n; j++) {
if (frame[i] == pages[j]) {
if (j > farthest) {
farthest = j;
res = i;
}
break;
}
}
if (j == n)
return i;}
return res == -1 ? 0 : res;
}
//Optimal
void simulateOptimal(int pages[], int n, int frames) {
int frame[MAX_FRAMES];
int i, j, k, pageFaults = 0;
int found;
for (i = 0; i < frames; i++) frame[i] = -1;
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < frames; j++) {
if (frame[j] == pages[i]) {
found = 1;
break;
}
}
if (!found) {
int empty = -1;
for (j = 0; j < frames; j++) {
if (frame[j] == -1) {
empty = j;
break;
}
}
if (empty != -1)
frame[empty] = pages[i];
else {
int idx = predict(pages, frame, n, i + 1, frames);
frame[idx] = pages[i];
}
pageFaults++;
}
printf("Step %2d: ", i + 1);
for (k = 0; k < frames; k++) {
if (frame[k] != -1)
printf("%d ", frame[k]);
else
printf("- ");
}
printf("\n");
}
printf("Total Page Faults (Optimal): %d\n", pageFaults);
}
PROGRAM-10
Write a C program to simulate the Paging memory management scheme
#include <stdio.h>
int main() {
int pageTable[100],i;
int noOfPages, noOfFrames, pageSize;
int logicalAddress, pageNumber, offset, physicalAddress;
printf("Enter number of pages: ");
scanf("%d", &noOfPages);
printf("Enter page size (in bytes): ");
scanf("%d", &pageSize);
printf("Enter number of frames: ");
scanf("%d", &noOfFrames);
printf("\nEnter the frame number for each page (-1 if not in memory):\n");
for (i = 0; i < noOfPages; i++) {
printf("Page %d: ", i);
scanf("%d", &pageTable[i]);
}
printf("\n--- Logical to Physical Address Translation ---\n");
char choice;
do {
printf("\nEnter a logical address (0 to %d): ", (noOfPages * pageSize) - 1);
scanf("%d", &logicalAddress);
pageNumber = logicalAddress / pageSize;
offset = logicalAddress % pageSize;
if (pageNumber >= noOfPages || pageTable[pageNumber] == -1) {
printf("Page fault! Page %d is not in memory.\n", pageNumber);
}
else {
physicalAddress = pageTable[pageNumber] * pageSize + offset;
printf("Logical Address %d --> Physical Address: %d\n", logicalAddress, physicalAddress);
}
printf("\nDo you want to translate another address? (y/n): ");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}

You might also like