0% found this document useful (0 votes)
57 views

OS Lab Manual

This document outlines OS lab programs that simulate different CPU scheduling algorithms: FCFS, SJF, Round Robin, and Priority Scheduling. For each algorithm, it provides the code to calculate processes' waiting times and turnaround times. The FCFS, SJF, and Priority Scheduling code samples include structs to represent processes with IDs, arrival or burst times. The Round Robin code implements a time quantum. Overall, the document provides C code examples to model and analyze different scheduling algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

OS Lab Manual

This document outlines OS lab programs that simulate different CPU scheduling algorithms: FCFS, SJF, Round Robin, and Priority Scheduling. For each algorithm, it provides the code to calculate processes' waiting times and turnaround times. The FCFS, SJF, and Priority Scheduling code samples include structs to represent processes with IDs, arrival or burst times. The Round Robin code implements a time quantum. Overall, the document provides C code examples to model and analyze different scheduling algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

OS Lab Programs

Sem:3rd Dr Ganesha M

1. Develop a c program to implement the Process system calls (fork (), exec(), wait(),
createprocess,terminate process)
a. Single process
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t child_pid;
int status;
// Create a child process
child_pid = fork();
if (child_pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (child_pid == 0) {
// Child process
printf("Child process (PID: %d) is running.\n", getpid());
// Replace the child process with a new program
execlp("/bin/ls", "ls", "-l", NULL);
// If exec fails, the code below will be executed
perror("Exec failed");
exit(1);

1
} else {
// Parent process
printf("Parent process (PID: %d) created a child (PID: %d).\n", getpid(), child_pid);
// Wait for the child process to finish
wait(&status);
if (WIFEXITED(status)) {
printf("Child process (PID: %d) exited with status %d.\n", child_pid,
WEXITSTATUS(status));
} else {
printf("Child process (PID: %d) did not exit normally.\n", child_pid);
}
}
return 0;
}
b. Multiple processes
// C program to demonstrate waitpid()
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

void waitexample()
{
int i, stat;
pid_t pid[5];
for (i=0; i<5; i++)
{
if ((pid[i] = fork()) == 0)
{

2
sleep(1);
exit(100 + i);
}
}
// Using waitpid() and printing exit status of children.

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


{
pid_t cpid = waitpid(pid[i], &stat, 0);
if (WIFEXITED(stat))
printf("Child %d terminated with status: %d\n",
cpid, WEXITSTATUS(stat));
}
}
// Driver code
int main()
{
waitexample();
return 0;
}

3
2)Simulate the following CPU scheduling algorithms to find turnaround time and waiting time

a)FCFS
b) SJF
c) Round Robin
d) Priority.

c. FCFS
#include <stdio.h>

struct Process {
int pid; // Process ID
int arrival; // Arrival time
int burst; // Burst time
};

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


int currentTime = 0;

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

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


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

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


int turnaroundTime = waitingTime + processes[i].burst;

printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].arrival, processes[i].burst,


waitingTime, turnaroundTime);

4
currentTime += processes[i].burst;
}

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

int n = sizeof(processes) / sizeof(processes[0]);

fcfsScheduling(processes, n);

return 0;
}

5
d. SJF
#include <stdio.h>

struct Process {
int pid; // Process ID
int burst; // Burst time
};

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


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

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


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

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


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

float total_wt = 0, total_tat = 0;

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

6
for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
printf("%d\t%d\t\t%d\t\t%d\n", proc[i].pid, proc[i].burst, wt[i], tat[i]);
}

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


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

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


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

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

7
struct Process proc[n];

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


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

sortProcesses(proc, n);

findAverageTime(proc, n);

return 0;
}

8
e. Round Robin
#include <stdio.h>

struct Process {
int pid; // Process ID
int burst; // Burst time
};

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


int remaining[n];
int currentTime = 0;

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


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

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

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


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

9
printf("Process %d executed for remaining time %d\n", processes[i].pid, remaining[i]);
}
}
}

if (allDone)
break;
}
}

int main() {
struct Process processes[] = {
{1, 10},
{2, 5},
{3, 8},
{4, 12}
};

int n = sizeof(processes) / sizeof(processes[0]);


int timeQuantum = 4;

roundRobinScheduling(processes, n, timeQuantum);

return 0;
}

10
f. Priority Scheduling
/******************************************************************************

Welcome to GDB Online.


GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite,
Prolog.
Code, Compile, Run and Debug online from anywhere in world.

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

// Maximum number of processes


#define MAX_PROCESSES 10

// Process structure
typedef struct Process {
int id; // Process ID
int priority; // Priority of the process (lower value indicates higher priority)
int burst_time; // Burst time (time required to complete the process)
} Process;

// Function to initialize processes


void initializeProcesses(Process processes[], int num_processes) {
for (int i = 0; i < num_processes; i++) {
processes[i].id = i;
printf("Enter priority for Process %d: ", i);
scanf("%d", &processes[i].priority);

11
printf("Enter burst time for Process %d: ", i);
scanf("%d", &processes[i].burst_time);
}
}

// Function to perform Priority Scheduling


void priorityScheduling(Process processes[], int num_processes) {
// Sort processes based on priority (lower priority comes first)
for (int i = 0; i < num_processes - 1; i++) {
for (int j = 0; j < num_processes - i - 1; j++) {
if (processes[j].priority > processes[j + 1].priority) {
// Swap processes
Process temp = processes[j];
processes[j] = processes[j + 1];
processes[j + 1] = temp;
}
}
}

int total_time = 0;
double average_waiting_time = 0.0;

printf("\nProcess Execution Order:\n");


for (int i = 0; i < num_processes; i++) {
printf("Process %d (Priority %d) is executing for %d seconds.\n",
processes[i].id, processes[i].priority, processes[i].burst_time);

total_time += processes[i].burst_time;
average_waiting_time += total_time;

12
// Waiting time for the next process (waiting time = total time so far)
average_waiting_time += total_time;
}

average_waiting_time /= num_processes;

printf("\nAverage Waiting Time: %.2lf seconds\n", average_waiting_time);


}

int main() {
int num_processes;

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


scanf("%d", &num_processes);

if (num_processes <= 0 || num_processes > MAX_PROCESSES) {


printf("Invalid number of processes. Please enter a valid number.\n");
return 1;
}

Process processes[MAX_PROCESSES];
initializeProcesses(processes, num_processes);

priorityScheduling(processes, num_processes);

return 0;
}

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

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

#define BUFFER_SIZE 20

sem_t empty, full;


int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int size=50;
void* producer(void* arg) {
int item = 1;

while (1) {
sem_wait(&empty);

buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
item++;

sem_post(&full);
if(item>size){
break;
}

14
}
printf("Sending completed\n ");

pthread_exit(NULL);
}

void* consumer(void* arg) {


int item;

while (1) {
sem_wait(&full);

item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;

sem_post(&empty);
if(item==size){
printf("Received all");
break;
}
}

pthread_exit(NULL);
}

int main() {
pthread_t producer_thread, consumer_thread;

15
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);

pthread_create(&producer_thread, NULL, producer, NULL);


pthread_create(&consumer_thread, NULL, consumer, NULL);

pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);

sem_destroy(&empty);
sem_destroy(&full);

return 0;
}

16
3. Develop a C program which demonstrates interprocess communication between a reader
process and a writer process. Use mkfifo, open, read, write and close APIs in your program.
A Write First
// C program to implement one side of FIFO

// This side writes first, then reads


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

int main()
{
int fd;

// FIFO file path


char * myfifo = "/tmp/myfifo";

// Creating the named file(FIFO)


// mkfifo(<pathname>, <permission>)
mkfifo(myfifo, 0666);

char arr1[80], arr2[80];


while (1)
{
// Open FIFO for write only
fd = open(myfifo, O_WRONLY);

17
// Take an input arr2ing from user.
// 80 is maximum length
fgets(arr2, 80, stdin);

// Write the input arr2ing on FIFO


// and close it
write(fd, arr2, strlen(arr2)+1);
close(fd);

// Open FIFO for Read only


fd = open(myfifo, O_RDONLY);

// Read from FIFO


read(fd, arr1, sizeof(arr1));

// Print the read message


printf("User2: %s\n", arr1);
close(fd);
}
return 0;
}

18
b. Read First
// C program to implement one side of FIFO
// This side reads first, then reads
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
int fd1;

// FIFO file path


char * myfifo = "/tmp/myfifo";

// Creating the named file(FIFO)


// mkfifo(<pathname>,<permission>)
mkfifo(myfifo, 0666);

char str1[80], str2[80];


while (1)
{
// First open in read only and read
fd1 = open(myfifo,O_RDONLY);
read(fd1, str1, 80);

// Print the read string and close

19
printf("User1: %s\n", str1);
close(fd1);

// Now open in write mode and write


// string taken from user.
fd1 = open(myfifo,O_WRONLY);
fgets(str2, 80, stdin);
write(fd1, str2, strlen(str2)+1);
close(fd1);
}
return 0;
}

20
4. Develop a C program to simulate Bankers Algorithm for Deadlock Avoidance..
a. Single process allotment
#include <stdio.h>
#include <stdbool.h>

// Define the number of processes and resources


#define NUM_PROCESSES 5
#define NUM_RESOURCES 3

// Maximum resources needed by each process


int max[NUM_PROCESSES][NUM_RESOURCES] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}
};

// Currently allocated resources for each process


int allocation[NUM_PROCESSES][NUM_RESOURCES] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};

// Available resources
int available[NUM_RESOURCES] = {3, 3, 2};

21
// Need resources for each process
int need[NUM_PROCESSES][NUM_RESOURCES];

// Function to calculate the need matrix


void calculateNeedMatrix() {
for (int i = 0; i < NUM_PROCESSES; i++) {
for (int j = 0; j < NUM_RESOURCES; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}

// Function to check if a process can be granted resources


bool canGrantResources(int process, int request[]) {
for (int i = 0; i < NUM_RESOURCES; i++) {
if (request[i] > need[process][i] || request[i] > available[i]) {
return false;
}
}
return true;
}

// Function to simulate resource allocation


void allocateResources(int process, int request[]) {
for (int i = 0; i < NUM_RESOURCES; i++) {
allocation[process][i] += request[i];
available[i] -= request[i];
need[process][i] -= request[i];

22
}
}

int main() {
calculateNeedMatrix();

int requestProcess = 1;
int request[NUM_RESOURCES] = {1, 2, 2};

if (canGrantResources(requestProcess, request)) {
allocateResources(requestProcess, request);
printf("Resources granted to process %d.\n", requestProcess);
printf("Updated allocation matrix:\n");
for (int i = 0; i < NUM_PROCESSES; i++) {
for (int j = 0; j < NUM_RESOURCES; j++) {
printf("%d ", allocation[i][j]);
}
printf("\n");
}
} else {
printf("Resources cannot be granted to process %d.\n", requestProcess);
}

return 0;
}

23
b. Multiple process allottment
// Banker's Algorithm
#include <stdio.h>

int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
int avail[3] = { 3, 3, 2 }; // Available Resources
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];

24
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;

25
}
}
if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);
// This code is contributed by Deep Baldha (CandyZack)
}

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

a. Worst fit
#include <stdio.h>

// Define the maximum number of memory blocks


#define MAX_BLOCKS 100

// Structure to represent memory blocks


struct MemoryBlock {
int block_id;
int size;
int allocated;
};

// Function to perform worst-fit memory allocation


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

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


if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (worstIdx == -1 || blocks[i].size > blocks[worstIdx].size) {
worstIdx = i;
}
}
}

if (worstIdx != -1) {

27
// Allocate the memory block
blocks[worstIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, worstIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}
}

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

struct MemoryBlock blocks[MAX_BLOCKS];

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


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

int n; // Number of processes


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

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


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

28
scanf("%d", &processSize);
worstFit(blocks, m, processSize);
}

return 0;
}

b. Best fit
#include <stdio.h>

// Define the maximum number of memory blocks


#define MAX_BLOCKS 100

// Structure to represent memory blocks


struct MemoryBlock {
int block_id;
int size;
int allocated;
};

// Function to perform best-fit memory allocation


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

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


if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (bestIdx == -1 || blocks[i].size < blocks[bestIdx].size) {
bestIdx = i;
}

29
}
}

if (bestIdx != -1) {
// Allocate the memory block
blocks[bestIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, bestIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}
}

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

struct MemoryBlock blocks[MAX_BLOCKS];

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


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

int n; // Number of processes


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

30
for (int i = 0; i < n; i++) {
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
bestFit(blocks, m, processSize);
}

return 0;
}

b1. Best fit


#include <stdio.h>

// Number of memory blocks


#define NUM_BLOCKS 5

// Number of processes
#define NUM_PROCESSES 5

// Sizes of memory blocks


int memory_blocks[NUM_BLOCKS] = {100, 500, 200, 300, 600};

// Sizes of processes
int process_sizes[NUM_PROCESSES] = {212, 417, 112, 426, 112};

// Array to keep track of whether a block is allocated or not


int allocated[NUM_BLOCKS] = {0};

31
// Function to perform Best Fit memory allocation
void bestFit() {
for (int i = 0; i < NUM_PROCESSES; i++) {
int best_fit_index = -1;
for (int j = 0; j < NUM_BLOCKS; j++) {
if (!allocated[j] && memory_blocks[j] >= process_sizes[i]) {
if (best_fit_index == -1 || memory_blocks[j] < memory_blocks[best_fit_index]) {
best_fit_index = j;
}
}
}

if (best_fit_index != -1) {
allocated[best_fit_index] = 1;
printf("Process %d (size %d) is allocated to Block %d (size %d)\n",
i, process_sizes[i], best_fit_index, memory_blocks[best_fit_index]);
} else {
printf("Process %d (size %d) cannot be allocated\n", i, process_sizes[i]);
}
}
}

int main() {
bestFit();

return 0;
}

32
c. First fit
#include <stdio.h>

// Define the maximum number of memory blocks


#define MAX_BLOCKS 100

// Structure to represent memory blocks


struct MemoryBlock {
int block_id;
int size;
int allocated;
};

// Function to perform first-fit memory allocation


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

int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");

33
scanf("%d", &m);

struct MemoryBlock blocks[MAX_BLOCKS];

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


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

int n; // Number of processes


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

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


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

return 0;
}

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

a. FIFO
#include <stdio.h>
int main()
{
int incomingStream[] = {4 , 1 , 2 , 4 , 5,4,1,2,3,6};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;
pages = sizeof(incomingStream)/sizeof(incomingStream[0]);
printf(" Incoming \t Frame 1 \t Frame 2 \t Frame 3 ");
int temp[ frames ];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}

35
pageFaults++;
if((pageFaults <= frames) && (s == 0))
{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}
printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}

36
b. LRU
#include<stdio.h>
#include<limits.h>

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

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


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

return 0;
}

void printFrame(int queue[], int occupied)


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

int main()
{

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


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

int n = sizeof(incomingStream)/sizeof(incomingStream[0]);
int frames = 3;

37
int queue[n];
int distance[n];
int occupied = 0;
int pagefault = 0;

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

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


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

if(checkHit(incomingStream[i], queue, occupied)){


printFrame(queue, occupied);
}

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


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

printFrame(queue, occupied);
}
else{

int max = INT_MIN;

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

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

// find frame item with max distance for LRU


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

printf("\n");

39
}

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

return 0;
}

40
7. Simulate following File Organization Techniques:
a) Single level directory
b)Two level directory

a. Single level directrry


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

// Maximum number of files in the directory


#define MAX_FILES 100

// Maximum file name length


#define MAX_NAME_LENGTH 256

// File structure to represent files


typedef struct File {
char name[MAX_NAME_LENGTH];
int size;
char content[1024]; // For simplicity, we use a fixed content size
} File;

// Directory structure to hold files


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

// Function to create a new file


File createFile(const char* name, int size, const char* content) {

41
File newFile;
strncpy(newFile.name, name, MAX_NAME_LENGTH);
newFile.size = size;
strncpy(newFile.content, content, sizeof(newFile.content));
return newFile;
}

// Function to add a file to the directory


void addFileToDirectory(Directory* directory, File file) {
if (directory->num_files < MAX_FILES) {
directory->files[directory->num_files] = file;
directory->num_files++;
} else {
printf("Directory is full. Cannot add more files.\n");
}
}

// Function to display the contents of the directory


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

int main() {
Directory directory;
directory.num_files = 0;

42
// Create and add files to the directory
File file1 = createFile("File1.txt", 100, "This is the content of File1.");
addFileToDirectory(&directory, file1);

File file2 = createFile("File2.txt", 200, "Content of File2 goes here.");


addFileToDirectory(&directory, file2);

// Display the directory contents


displayDirectoryContents(&directory);

return 0;
}

43
b. Two level directory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_DIRS 100


#define MAX_FILES 100

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

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

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

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


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

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

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

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

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


}

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


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

strcpy(directories[i].files[directories[i].num_files].name, file_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;

45
printf("File %s created in %s.\n", file_name, dir_name);
return;
}
}

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


}

void listFiles(char dir_name[]) {


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

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


}

int main() {
strcpy(directories[0].name, "root");
directories[0].num_files = 0;
num_dirs++;

char parent[50], dir[50], file[50];

46
createDirectory("root", "docs");
createDirectory("root", "images");
createFile("docs", "document1.txt");
createFile("docs", "document2.txt");
createFile("images", "image1.jpg");
listFiles("docs");
listFiles("images");

return 0;
}

47
8. Develop a C program to simulate the Linked file allocation strategies.
#include <stdio.h>
#include <stdlib.h>
int main(){
int f[50], p, i, st, len, j, c, k, a;
for (i = 0; i < 50; i++)
f[i] = 0;
printf("Enter how many blocks already allocated: ");
scanf("%d", &p);
printf("Enter blocks already allocated: ");
for (i = 0; i < p; i++) {
scanf("%d", &a);
f[a] = 1;
}
x:
printf("Enter index starting block and length: ");
scanf("%d%d", &st, &len);
k = len;
if (f[st] == 0)
{
for (j = st; j < (st + k); j++){
if (f[j] == 0){
f[j] = 1;
printf("%d --- >", j);
}
else{
//printf("%d Block is already allocated \n", j);
k++;
}

48
}
}
else
printf("%d starting block is already allocated \n", st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if (c == 1)
goto x;
else
exit(0);
return 0;
}

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

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

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

52

You might also like