You are on page 1of 36

OPERATING SYSTEMS - BCS303 III SEM B.

1. Develop a c program to implement the Process system calls (fork (), exec(),
wait(), create process, 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);
}
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);
}
}

1
OPERATING SYSTEMS - BCS303 III SEM B.E

return 0;
}

OUTPUT
Child process (PID: 48492) is running.
total 44
-rw-r--r-- 1 compiler compiler 2 Nov 9 06:55 Employee.txt
-rw-r--r-- 1 compiler compiler 16 Nov 9 08:20 INPUT.txt
-rw-r--r-- 1 compiler compiler 0 Nov 9 06:28 Students.dat
-rw-r--r-- 1 compiler compiler 11 Nov 9 07:52 archivo.txt
-rw-r--r-- 1 compiler compiler 84 Nov 9 06:55 car_data.txt
-rw-r--r-- 1 compiler compiler 35 Nov 9 07:12 example.txt
-rw-r--r-- 1 compiler compiler 35 Nov 9 07:11 o.out
-rw-r--r-- 1 compiler compiler 36 Nov 9 06:49 result.dat
-rw-r--r-- 1 compiler compiler 2709 Nov 9 08:53 sorting_comparison.csv
-rw-r--r-- 1 compiler compiler 96 Nov 9 06:36 student.dat
-rw-r--r-- 1 compiler compiler 21 Nov 9 06:30 swap.txt
-rw-r--r-- 1 compiler compiler 2003 Nov 9 09:09 zapis.txt

a. Multiple processes

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

int main() {
int num_processes = 5; // Number of child processes to create
pid_t child_pid;

printf("Parent process (PID: %d)\n", getpid());

for (int i = 1; i <= num_processes; ++i)


{
child_pid = fork();
if (child_pid == -1)
{
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (child_pid == 0)
{
// Code executed by child processes
printf("Child process %d (PID: %d, Parent PID: %d)\n", i, getpid(), getppid());

2
OPERATING SYSTEMS - BCS303 III SEM B.E

// Execute different commands in each child process


if (i == 1)
{
execl("/bin/ls", "ls", "-l", NULL);
}
else if (i == 2)
{
execl("/bin/pwd", "pwd", NULL);
}
else if (i == 3)
{
execl("/bin/ps", "ps", NULL);
}
else if (i == 4)
{
execl("/bin/date", "date", NULL);
}
else if (i == 5)
{
execl("/bin/echo", "echo", "Hello from child process", NULL);
}
else
{
printf("Invalid child process number\n");
}

// If execl fails
perror("Exec failed");
exit(EXIT_FAILURE);
}
}
// Parent process waits for all child processes to complete
for (int i = 1; i <= num_processes; ++i) {
wait(NULL);
}
printf("Parent process exiting\n");
return 0;
}

OUTPUT
Parent process (PID: 46100)
Child process 1 (PID: 46101, Parent PID: 46100)
Child process 2 (PID: 46102, Parent PID: 46100)
Child process 3 (PID: 46103, Parent PID: 46100)
Child process 4 (PID: 46104, Parent PID: 46100)
Child process 5 (PID: 46105, Parent PID: 46100)

3
OPERATING SYSTEMS - BCS303 III SEM B.E

Hello from child process


/home/compiler
Thu Nov 9 09:39:06 UTC 2023
total 4
-rw-r--r-- 1 compiler compiler 6 Nov 9 08:17 'BHAVAN KALYAN'
-rw-r--r-- 1 compiler compiler 0 Nov 9 09:34 output.txt
-rw-r--r-- 1 compiler compiler 0 Nov 9 06:09 sample.txt
PID TTY TIME CMD
46093 pts/169 00:00:00 dash
46100 pts/169 00:00:00 kPVgeBKZ5k.o
46103 pts/169 00:00:00 ps
Parent process exiting

4
OPERATING SYSTEMS - BCS303 III SEM B.E

2. Simulate the following CPU scheduling algorithms to find turnaround time and waiting
time a) FCFS b) SJF c) Round Robin d) Priority.

a. 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);
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;
}

OUTPUT
Process Arrival Time Burst Time Waiting Time Turnaround Time
1 0 6 0 6

5
OPERATING SYSTEMS - BCS303 III SEM B.E

2 2 3 4 7
3 3 8 6 14

6
OPERATING SYSTEMS - BCS303 III SEM B.E

b. 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");
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);
}

7
OPERATING SYSTEMS - BCS303 III SEM B.E

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);
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;
}

OUTPUT
Enter the number of processes: 5
Enter burst time for process 1: 5
Enter burst time for process 2: 12
Enter burst time for process 3: 8
Enter burst time for process 4: 4
Enter burst time for process 5: 3
Process Burst Time Waiting Time Turnaround Time
5 3 0 3
4 4 3 7
1 5 7 12
3 8 12 20
2 12 20 32
Average waiting time = 8.40
Average turnaround time = 14.80

8
OPERATING SYSTEMS - BCS303 III SEM B.E

c. 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;
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}
};

9
OPERATING SYSTEMS - BCS303 III SEM B.E

int n = sizeof(processes) /
sizeof(processes[0]);
int timeQuantum = 4;
roundRobinScheduling(processes, n, timeQuantum);
return 0;
}

OUTPUT
Process 1 executed for time quantum 4
Process 2 executed for time quantum 4
Process 3 executed for time quantum 4
Process 4 executed for time quantum 4
Process 1 executed for time quantum 4
Process 2 executed for remaining time 0
Process 3 executed for remaining time 0
Process 4 executed for time quantum 4
Process 1 executed for remaining time 0
Process 4 executed for remaining time 0

10
OPERATING SYSTEMS - BCS303 III SEM B.E

d. Priority Scheduling
#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
OPERATING SYSTEMS - BCS303 III SEM B.E

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
OPERATING SYSTEMS - BCS303 III SEM B.E

// 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;
}

Enter the number of processes: 4


Enter priority for Process 0: 3
Enter burst time for Process 0: 4
Enter priority for Process 1: 2
Enter burst time for Process 1: 5
Enter priority for Process 2: 1
Enter burst time for Process 2: 6
Enter priority for Process 3: 6
Enter burst time for Process 3: 7
Process Execution Order:
Process 2 (Priority 1) is executing for 6 seconds.
Process 1 (Priority 2) is executing for 5 seconds.
Process 0 (Priority 3) is executing for 4 seconds.
Process 3 (Priority 6) is executing for 7 seconds.

Average Waiting Time: 27.00 seconds

13
OPERATING SYSTEMS - BCS303 III SEM B.E

3. 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;
}
}
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);
}

14
OPERATING SYSTEMS - BCS303 III SEM B.E

int main()
{
pthread_t producer_thread, consumer_thread;
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;
}

Compilation command
gcc –pthread producer-consumer.c –o producer-consumer

4. 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);

15
OPERATING SYSTEMS - BCS303 III SEM B.E

// 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;
}

16
OPERATING SYSTEMS - BCS303 III SEM B.E

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
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;
}

17
OPERATING SYSTEMS - BCS303 III SEM B.E

5. Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance..


a. Single process allottment
#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};
// 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;
}
}

18
OPERATING SYSTEMS - BCS303 III SEM B.E

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];
}
}
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;
}

OUTPUT
Resources granted to process 1.
Updated allocation matrix:
010
322
302
211
002

19
Dr. T. Thimmaiah Institute of Technology, KGF

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];
}
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];

Operating Systems (BCS303)


20
Dr. T. Thimmaiah Institute of Technology, KGF
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;

}
}
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);
}

Operating Systems (BCS303)


21
Dr. T. Thimmaiah Institute of Technology, KGF

6. 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) {
// 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;

Operating Systems (BCS303)


22
Dr. T. Thimmaiah Institute of Technology, KGF
printf("Enter the size of process %d: ", i + 1);

Operating Systems (BCS303)


23
Dr. T. Thimmaiah Institute of Technology, KGF

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;
}
}
}
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);

Operating Systems (BCS303)


24
Dr. T. Thimmaiah Institute of Technology, KGF
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};
// 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;
}

Operating Systems (BCS303)


25
Dr. T. Thimmaiah Institute of Technology, KGF
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: ");
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;
}

Operating Systems (BCS303)


26
Dr. T. Thimmaiah Institute of Technology, KGF
7. 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--;
}
}

Operating Systems (BCS303)


27
Dr. T. Thimmaiah Institute of Technology, KGF

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;
}

Operating Systems (BCS303)


28
Dr. T. Thimmaiah Institute of Technology, KGF

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;
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;

Operating Systems (BCS303)


29
Dr. T. Thimmaiah Institute of Technology, KGF
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");
}
printf("Page Fault: %d",pagefault);
return 0;
}

8. 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

Operating Systems (BCS303)


30
Dr. T. Thimmaiah Institute of Technology, KGF
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) {
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;
// 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;
}
b. Two level
directory #include
<stdio.h> #include
<stdlib.h> #include
<string.h>
#define MAX_DIRS 100
#define MAX_FILES 100
struct FileEntry {

Operating Systems (BCS303)


31
Dr. T. Thimmaiah Institute of Technology, KGF
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++) {
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++;
printf("File %s created in %s.\n", file_name, dir_name);
return;
}
}
printf("Error: Directory not found.\n");

Operating Systems (BCS303)


32
Dr. T. Thimmaiah Institute of Technology, KGF
}
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];
createDirectory("root", "docs");
createDirectory("root", "images");
createFile("docs",
"document1.txt");
createFile("docs",
"document2.txt");
createFile("images", "image1.jpg");
listFiles("docs");
listFiles("images");
return 0;
}

Operating Systems (BCS303)


33
Dr. T. Thimmaiah Institute of Technology, KGF

9. 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++;
}
}
}
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;
}

10. 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],

Operating Systems (BCS303)


34
Dr. T. Thimmaiah Institute of Technology, KGF
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++;

Operating Systems (BCS303)


35
Dr. T. Thimmaiah Institute of Technology, KGF

}
}
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];
//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;
}

Operating Systems (BCS303)


36

You might also like