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

M Tech-Practicals

The document outlines several programming experiments related to process management and synchronization in operating systems. It includes programs for creating processes, displaying process IDs, file copying, multithreading, CPU scheduling algorithms, the producer-consumer problem using semaphores, and simulating the Banker's algorithm for deadlock avoidance. Each experiment is accompanied by a description and source code in C, demonstrating various system calls and concepts.

Uploaded by

bhushan123077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views40 pages

M Tech-Practicals

The document outlines several programming experiments related to process management and synchronization in operating systems. It includes programs for creating processes, displaying process IDs, file copying, multithreading, CPU scheduling algorithms, the producer-consumer problem using semaphores, and simulating the Banker's algorithm for deadlock avoidance. Each experiment is accompanied by a description and source code in C, demonstrating various system calls and concepts.

Uploaded by

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

Experiment No.

-1

Write a prgram to create a new process that exec new program using system calls fork(),execlp(), and wait().

Description:-

 The parent process creates a child using fork().

 The child process uses execlp() to run a different program (e.g., ls command).

 The parent process waits for the child to complete using wait().

Program:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/wait.h>

int main() {

pid_t pid;

// Create a new process

pid = fork();

if (pid < 0) {

// Error occurred

perror("fork failed");

exit(EXIT_FAILURE);

} else if (pid == 0) {

// Child process

printf("Child process running 'ls -l'\n");

execlp("ls", "ls", "-l", NULL);

// If execlp fails

perror("execlp failed");

exit(EXIT_FAILURE);

} else {

// Parent process

printf("Parent waiting for child process...\n");

wait(NULL); // Wait for child to finish

printf("Child process finished.\n");

return 0;

Experiment No.-2
Write a program to display PID and PPID using system calls getpid() & getppid()

Description:-

getpid() returns the Process ID of the calling process.

getppid() returns the Parent Process ID of the calling process.

Program :

#include <stdio.h>

#include <unistd.h>

int main() {

pid_t pid = getpid(); // Get current process ID

pid_t ppid = getppid(); // Get parent process ID

printf("Current Process ID (PID): %d\n", pid);

printf("Parent Process ID (PPID): %d\n", ppid);

return 0;

}
Experiment No.-3

Write a program using I/O system calls open(),read() & write() to copy contents of one file to another file.

Description:

Uses open() to open the source file in read-only mode.

Uses open() (with flags) to create or truncate the destination file in write-only mode.

Uses read() to read data from the source file.

Uses write() to write data to the destination file.

Includes error handling for system calls.

Program:

#include <stdio.h>

#include <stdlib.h>

#include <fcntl.h>

#include <unistd.h>

#define BUFFER_SIZE 1024

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

int src_fd, dest_fd;

char buffer[BUFFER_SIZE];

ssize_t bytes_read, bytes_written;

if (argc != 3) {

fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]);

exit(EXIT_FAILURE);

// Open source file for reading

src_fd = open(argv[1], O_RDONLY);

if (src_fd < 0) {

perror("Failed to open source file");

exit(EXIT_FAILURE);

// Open/create destination file for writing

dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (dest_fd < 0) {

perror("Failed to open/create destination file");


close(src_fd);

exit(EXIT_FAILURE);

// Read from source and write to destination

while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) {

bytes_written = write(dest_fd, buffer, bytes_read);

if (bytes_written != bytes_read) {

perror("Failed to write to destination file");

close(src_fd);

close(dest_fd);

exit(EXIT_FAILURE);

} if (bytes_read < 0) {

perror("Failed to read from source file");

// Close files

close(src_fd);

close(dest_fd);

printf("File copied successfully.\n");

return 0;

Experiment No.-4

Process Management Write a program to implement multithreaded program using pthreads.

Description :

Process Management :

Process Management is a key function of any operating system (OS). It involves creating, scheduling, and
terminating processes — where a process is a running instance of a program.

ey Concepts in Process Management:


1. Process
An executing instance of a program.

Has a Process ID (PID).

Contains:

Program code

Stack

Data

Heap

Registers and program counter

2. Process States
Typical states in a process lifecycle:
css
CopyEdit
[New] → [Ready] → [Running] → [Waiting] → [Terminated]

3. Process Control Block (PCB)


A data structure maintained by the OS to keep info about each process:

PID

Process state

CPU registers

Memory limits

Open files

4. Operations on Processes
Creation: fork() in UNIX, CreateProcess() in Windows

Execution: exec() replaces current process image

Termination: exit(), kill()

A multithreaded C program using pthreads that creates multiple threads, where each thread runs a function
independently. This is a basic and clear example of process management with threads.

Uses pthread_create() to spawn threads.

Each thread executes a function and prints a message.

The main thread waits for all threads to complete using pthread_join().

Program:

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#define NUM_THREADS 5

// Thread function

void *thread_task(void *arg) {

int thread_id = *((int *)arg);


printf("Thread %d: Hello from thread!\n", thread_id);

pthread_exit(NULL);

int main() {

pthread_t threads[NUM_THREADS];

int thread_ids[NUM_THREADS];

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

thread_ids[i] = i + 1;

if (pthread_create(&threads[i], NULL, thread_task, &thread_ids[i]) != 0) {

perror("Error creating thread");

exit(EXIT_FAILURE);

// Wait for all threads to complete

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

pthread_join(threads[i], NULL);

printf("Main thread: All threads have finished execution.\n");

return 0;

Experiment No.-5

Write a program to simulate the following CPU Scheduling algorithms a)FCFS b)SJF c)Priority d) Round Robin

Description:

 Input: Process ID, Burst Time, Arrival Time, and Priority (where applicable)

 Time Quantum is used in Round Robin

Program :

#include <stdio.h>

#include <stdlib.h>

#define MAX 100

typedef struct {

int pid, arrival_time, burst_time, priority;

int waiting_time, turnaround_time, remaining_time, completed;

} Process;

void fcfs(Process p[], int n);


void sjf(Process p[], int n);

void priority_scheduling(Process p[], int n);

void round_robin(Process p[], int n, int time_quantum);

void input_processes(Process p[], int *n) {

printf("Enter number of processes: ");

scanf("%d", n);

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

p[i].pid = i + 1;

printf("Process %d Arrival Time: ", p[i].pid);

scanf("%d", &p[i].arrival_time);

printf("Process %d Burst Time: ", p[i].pid);

scanf("%d", &p[i].burst_time);

printf("Process %d Priority (lower is higher priority): ", p[i].pid);

scanf("%d", &p[i].priority);

p[i].remaining_time = p[i].burst_time;

p[i].completed = 0;

void print_results(Process p[], int n) {

float avg_wt = 0, avg_tat = 0;

printf("\nPID\tAT\tBT\tWT\tTAT\n");

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

avg_wt += p[i].waiting_time;

avg_tat += p[i].turnaround_time;

printf("%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].arrival_time, p[i].burst_time,

p[i].waiting_time, p[i].turnaround_time);

printf("Average Waiting Time: %.2f\n", avg_wt / n);

printf("Average Turnaround Time: %.2f\n", avg_tat / n);

int main() {

Process p[MAX];

int n, choice, tq;

input_processes(p, &n);

do {

printf("\nCPU Scheduling Algorithms:\n");


printf("1. FCFS\n2. SJF\n3. Priority\n4. Round Robin\n5. Exit\n");

printf("Choose an option: ");

scanf("%d", &choice);

switch (choice) {

case 1:

fcfs(p, n);

break;

case 2:

sjf(p, n);

break;

case 3:

priority_scheduling(p, n);

break;

case 4:

printf("Enter Time Quantum: ");

scanf("%d", &tq);

round_robin(p, n, tq);

break;

case 5:

exit(0);

} while (choice != 5);

return 0;

// ---- FCFS ----

void fcfs(Process p[], int n) {

int time = 0;

Process temp[MAX];

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

temp[i] = p[i];

// Sort by arrival time

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

for (int j = i + 1; j < n; j++)

if (temp[i].arrival_time > temp[j].arrival_time) {

Process t = temp[i];

temp[i] = temp[j];
temp[j] = t;

time = temp[0].arrival_time;

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

temp[i].waiting_time = (time > temp[i].arrival_time ? time : temp[i].arrival_time) - temp[i].arrival_time;

time += temp[i].burst_time;

temp[i].turnaround_time = temp[i].waiting_time + temp[i].burst_time;

print_results(temp, n);

// ---- SJF ----

void sjf(Process p[], int n) {

int completed = 0, time = 0, min_idx;

Process temp[MAX];

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

temp[i] = p[i];

temp[i].completed = 0;

while (completed < n) {

int min_bt = 99999;

min_idx = -1;

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

if (temp[i].arrival_time <= time && !temp[i].completed && temp[i].burst_time < min_bt) {

min_bt = temp[i].burst_time;

min_idx = i;

if (min_idx == -1) {

time++;

} else {

temp[min_idx].waiting_time = time - temp[min_idx].arrival_time;

time += temp[min_idx].burst_time;

temp[min_idx].turnaround_time = time - temp[min_idx].arrival_time;

temp[min_idx].completed = 1;

completed++;

}
}

print_results(temp, n);

// ---- Priority Scheduling ----

void priority_scheduling(Process p[], int n) {

int completed = 0, time = 0, idx;

Process temp[MAX];

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

temp[i] = p[i];

temp[i].completed = 0;

while (completed < n) {

int min_pr = 99999;

idx = -1;

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

if (temp[i].arrival_time <= time && !temp[i].completed && temp[i].priority < min_pr) {

min_pr = temp[i].priority;

idx = i;

if (idx == -1) {

time++;

} else {

temp[idx].waiting_time = time - temp[idx].arrival_time;

time += temp[idx].burst_time;

temp[idx].turnaround_time = time - temp[idx].arrival_time;

temp[idx].completed = 1;

completed++;

print_results(temp, n);

// ---- Round Robin ----

void round_robin(Process p[], int n, int time_quantum) {

Process temp[MAX];
int time = 0, remain = n;

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

temp[i] = p[i];

temp[i].remaining_time = p[i].burst_time;

temp[i].waiting_time = 0;

while (remain > 0) {

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

if (temp[i].arrival_time <= time && temp[i].remaining_time > 0) {

int exec_time = (temp[i].remaining_time < time_quantum) ? temp[i].remaining_time : time_quantum;

time += exec_time;

temp[i].remaining_time -= exec_time;

if (temp[i].remaining_time == 0) {

temp[i].turnaround_time = time - temp[i].arrival_time;

temp[i].waiting_time = temp[i].turnaround_time - temp[i].burst_time;

remain--;

print_results(temp, n);

}
Experiment No.-6

Process Synchronization- Write a program to simulate producer –consumer problem using semaphores.

Description:

Process Synchronization :

Process Synchronization is a fundamental concept in operating systems that ensures multiple processes or
threads can coordinate their execution when sharing resources (like memory, files, or hardware) without causing race
conditions, deadlocks, or inconsistent data.

Common Synchronization Techniques:

Mutex (Mutual Exclusion)

Ensures only one thread enters the critical section at a time.

Semaphores

A signaling mechanism.

Types:

Binary Semaphore (0 or 1) — acts like a mutex.

Counting Semaphore — manages multiple instances of a resource.

Monitors

High-level construct that wraps data + operations + locking.

Found in languages like Java (via synchronized blocks/methods).

Condition Variables

Allows threads to wait for specific conditions to be true (e.g., queue not empty).

This program uses:

sem_t semaphores for synchronization.

A buffer (array) to hold produced items.

A mutex to ensure mutual exclusion.

Semaphores used:

empty – counts empty slots.

full – counts full slots.


mutex – protects critical section.

Program:

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];

int in = 0, out = 0;

sem_t empty, full;

pthread_mutex_t mutex;

void *producer(void *arg) {

int item;

while (1) {

item = rand() % 100; // Produce an item

sem_wait(&empty); // Decrement empty slots

pthread_mutex_lock(&mutex); // Enter critical section

buffer[in] = item;

printf("Producer produced: %d at %d\n", item, in);

in = (in + 1) % BUFFER_SIZE;

pthread_mutex_unlock(&mutex); // Exit critical section

sem_post(&full); // Increment full slots

sleep(1); // Simulate production time

void *consumer(void *arg) {


int item;

while (1) {

sem_wait(&full); // Wait if buffer is empty

pthread_mutex_lock(&mutex); // Enter critical section

item = buffer[out];

printf("Consumer consumed: %d from %d\n", item, out);

out = (out + 1) % BUFFER_SIZE;

pthread_mutex_unlock(&mutex); // Exit critical section

sem_post(&empty); // Increment empty slots

sleep(2); // Simulate consumption time

int main() {

pthread_t prod_thread, cons_thread;

// Initialize semaphores and mutex

sem_init(&empty, 0, BUFFER_SIZE);

sem_init(&full, 0, 0);

pthread_mutex_init(&mutex, NULL);

// Create producer and consumer threads

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

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

// Join threads (optional for this infinite example)

pthread_join(prod_thread, NULL);

pthread_join(cons_thread, NULL);

// Clean up (won’t be reached in this infinite loop)

sem_destroy(&empty);

sem_destroy(&full);

pthread_mutex_destroy(&mutex);
return 0;

Experiment No.-7

Deadlock Write a program to simulate Bankers algorithm for the purpose of deadlock avoidance.

Description:

The Banker's Algorithm is used in operating systems to avoid deadlock by ensuring resource allocation happens only if
it leads to a safe state.

Banker's Algorithm in Python

#include<stdio.h>

int main() {

/* array will store at most 5 process with 3 resoures if your process or

resources is greater than 5 and 3 then increase the size of array */

int p, c, count = 0, i, j, alc[5][3], max[5][3], need[5][3], safe[5], available[3], done[5], terminate = 0;

printf("Enter the number of process and resources");

scanf("%d %d", & p, & c);

// p is process and c is diffrent resources

printf("enter allocation of resource of all process %dx%d matrix", p, c);

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

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

scanf("%d", & alc[i][j]);

printf("enter the max resource process required %dx%d matrix", p, c);

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

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


scanf("%d", & max[i][j]);

printf("enter the available resource");

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

scanf("%d", & available[i]);

printf("\n need resources matrix are\n");

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

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

need[i][j] = max[i][j] - alc[i][j];

printf("%d\t", need[i][j]);

printf("\n");

/* once process execute variable done will stop them for again execution */

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

done[i] = 0;

while (count < p) {

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

if (done[i] == 0) {

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

if (need[i][j] > available[j])

break;

//when need matrix is not greater then available matrix then if j==c will true

if (j == c) {

safe[count] = i;

done[i] = 1;

/* now process get execute release the resources and add them in available resources */

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

available[j] += alc[i][j];

count++;

terminate = 0;
} else {

terminate++;

if (terminate == (p - 1)) {

printf("safe sequence does not exist");

break;

if (terminate != (p - 1)) {

printf("\n available resource after completion\n");

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

printf("%d\t", available[i]);

printf("\n safe sequence are\n");

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

printf("p%d\t", safe[i]);

return 0;

}
Experiment No.-8

Write a program to simulate deadlock detection

Description:

Deadlock occurs when a group is stuck in a process because everyone is hanging onto resources while waiting for other
ways to get them.

Detection of deadlocks:

The OS predicts a future deadlock with this plan of action. As a result, it runs a deadlock detection procedure
periodically and performs a recovery plan when it detects a dead draw.

The OS's main function is to identify the deadlock.

There are two methods for finding.

Deadlocks can be created through deadlock detection. After that, assess the system's condition to see if a
stalemate has occurred and resolve it. Tracking the allocation of resources and process status, rolling back,
restarting one or more processes, and breaking discovered deadlocks are all done using algorithms. Identifying
deadlocks is simple since the operating system's resource scheduler is aware of the resources that every process
has locked or is actively seeking.

For Each Resource in a Single Instance:


In the wait-for-graph method, the OS focuses on forming a circle. It resembles the Resource allocation graph (RAG), with
some differences. Most frequently, it combines RAG along with the Wait-for graph.

Each Resource in Multiple Instance:


For resources containing many instances, we use the Safety algorithm, which implements the same logic as the Banker's
algorithm. There isn't a maximum required resource matrix, but there are just the allocated, available, and present
requirements matrices.

Program:

1. #include <stdio.h>
2. #define MAX_PROCESSES 10
3. #define MAX_RESOURCES 10
4.
5. int allocation[MAX_PROCESSES][MAX_RESOURCES];
6. int request[MAX_PROCESSES][MAX_RESOURCES];
7. int available[MAX_RESOURCES];
8. int resources[MAX_RESOURCES];
9. int work[MAX_RESOURCES];
10. int marked[MAX_PROCESSES];
11.
12. int main() {
13. int num_processes, num_resources;
14.
15. printf("Enter the number of processes: ");
16. scanf("%d", &num_processes);
17.
18. printf("Enter the number of resources: ");
19. scanf("%d", &num_resources);
20.
21. // Input total resources
22. for (int i = 0; i < num_resources; i++) {
23. printf("Enter the total amount of Resource R%d: ", i + 1);
24. scanf("%d", &resources[i]);
25. }
26.
27. // Input request matrix
28. printf("Enter the request matrix:\n");
29. for (int i = 0; i < num_processes; i++) {
30. for (int j = 0; j < num_resources; j++) {
31. scanf("%d", &request[i][j]);
32. }
33. }
34.
35. // User Input allocation matrix
36. printf("Enter the allocation matrix:\n");
37. for (int i = 0; i < num_processes; i++) {
38. for (int j = 0; j < num_resources; j++) {
39. scanf("%d", &allocation[i][j]);
40. }
41. }
42.
43. // Initialization of the available resources
44. for (int j = 0; j < num_resources; j++) {
45. available[j] = resources[j];
46. for (int i = 0; i < num_processes; i++) {
47. available[j] -= allocation[i][j];
48. }
49. }
50.
51. // Mark processes with zero allocation
52. for (int i = 0; i < num_processes; i++) {
53. int count = 0;
54. for (int j = 0; j < num_resources; j++) {
55. if (allocation[i][j] == 0) {
56. count++;
57. } else {
58. break;
59. }
60. }
61. if (count == num_resources) {
62. marked[i] = 1;
63. }
64. }
65.
66. // Initialize work with available
67. for (int j = 0; j < num_resources; j++) {
68. work[j] = available[j];
69. }
70.
71. // Mark processes with requests <= work
72. for (int i = 0; i < num_processes; i++) {
73. int can_be_processed = 1;
74. if (marked[i] != 1) {
75. for (int j = 0; j < num_resources; j++) {
76. if (request[i][j] > work[j]) {
77. can_be_processed = 0;
78. break;
79. }
80. }
81. if (can_be_processed) {
82. marked[i] = 1;
83. for (int j = 0; j < num_resources; j++) {
84. work[j] += allocation[i][j];
85. }
86. }
87. }
88. }
89.
90. // Check for unmarked processes (deadlock)
91. int deadlock = 0;
92. for (int i = 0; i < num_processes; i++) {
93. if (marked[i] != 1) {
94. deadlock = 1;
95. break;
96. }
97. }
98.
99. if (deadlock) {
100. printf("Deadlock detected\n");
101. } else {
102. printf("No deadlock possible\n");
103. }
104.
105. return 0;
106. }

Experiment No.-9

Write a C Program to simulate page replacement algorithms a)FIFO 2) LRU c) LFU

C program that simulates the following Page Replacement Algorithms:

1. FIFO (First-In-First-Out)
2. LRU (Least Recently Used)
3. LFU (Least Frequently Used)

The user can choose which algorithm to run. The page reference string and number of frames are input
interactively.

#include <stdio.h>

#include <stdlib.h>
#include <limits.h>

#define MAX 100

// Function prototypes

void fifo(int pages[], int n, int capacity);

void lru(int pages[], int n, int capacity);

void lfu(int pages[], int n, int capacity);

int main() {

int n, capacity, choice;

int pages[MAX];

printf("Enter number of pages: ");

scanf("%d", &n);

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

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

scanf("%d", &pages[i]);

printf("Enter number of frames: ");

scanf("%d", &capacity);

printf("\nChoose the Page Replacement Algorithm:\n");

printf("1. FIFO\n2. LRU\n3. LFU\nEnter choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

fifo(pages, n, capacity);

break;

case 2:

lru(pages, n, capacity);

break;

case 3:

lfu(pages, n, capacity);
break;

default:

printf("Invalid choice.\n");

return 0;

// FIFO Page Replacement

void fifo(int pages[], int n, int capacity) {

int frames[capacity], front = 0, count = 0, faults = 0;

for (int i = 0; i < capacity; i++) frames[i] = -1;

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

int found = 0;

for (int j = 0; j < capacity; j++) {

if (frames[j] == pages[i]) {

found = 1;

break;

if (!found) {

frames[front] = pages[i];

front = (front + 1) % capacity;

faults++;

printf("Frame: ");

for (int k = 0; k < capacity; k++) {

if (frames[k] != -1)
printf("%d ", frames[k]);

else

printf("- ");

printf("\n");

printf("Total Page Faults (FIFO): %d\n", faults);

// LRU Page Replacement

void lru(int pages[], int n, int capacity) {

int frames[capacity], time[capacity];

int count = 0, faults = 0;

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

frames[i] = -1;

time[i] = 0;

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

int found = 0;

for (int j = 0; j < capacity; j++) {

if (frames[j] == pages[i]) {

found = 1;

time[j] = i;

break;

if (!found) {

int min = INT_MAX, pos = -1;


for (int j = 0; j < capacity; j++) {

if (frames[j] == -1) {

pos = j;

break;

} else if (time[j] < min) {

min = time[j];

pos = j;

frames[pos] = pages[i];

time[pos] = i;

faults++;

printf("Frame: ");

for (int k = 0; k < capacity; k++) {

if (frames[k] != -1)

printf("%d ", frames[k]);

else

printf("- ");

printf("\n");

printf("Total Page Faults (LRU): %d\n", faults);

// LFU Page Replacement

void lfu(int pages[], int n, int capacity) {


int frames[capacity], freq[capacity], time[capacity];

int faults = 0;

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

frames[i] = -1;

freq[i] = 0;

time[i] = 0;

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

int found = 0;

for (int j = 0; j < capacity; j++) {

if (frames[j] == pages[i]) {

freq[j]++;

time[j] = i;

found = 1;

break;

if (!found) {

int min_freq = INT_MAX, min_time = INT_MAX, pos = -1;

for (int j = 0; j < capacity; j++) {

if (frames[j] == -1) {

pos = j;

break;

} else if (freq[j] < min_freq || (freq[j] == min_freq && time[j] < min_time)) {
min_freq = freq[j];

min_time = time[j];

pos = j;

frames[pos] = pages[i];

freq[pos] = 1;

time[pos] = i;

faults++;

printf("Frame: ");

for (int k = 0; k < capacity; k++) {

if (frames[k] != -1)

printf("%d ", frames[k]);

else

printf("- ");

printf("\n");

printf("Total Page Faults (LFU): %d\n", faults);

Experiment No.-10

I/O System Write a program to simulate the following file organization techniques

a) Single level directory b) two Level directory.

Description:

 The Single Level Directory has all files in one directory.


 The Two Level Directory allows each user to have their own directory.
 Single Level Directory:
o All files share a common namespace.
o Operations: Create, Delete, Search, List.
 Two Level Directory:
o Each user has their own directory.
o Operations: Create User, then Create/Delete/Search files inside that user's directory.

#include <stdio.h>

#include <string.h>

#define MAX 100

// Struct for a file

typedef struct {

char filename[50];

} File;

// Struct for a user directory (used in two-level)

typedef struct {

char username[50];

File files[MAX];

int fileCount;

} UserDirectory;

// Function prototypes

void singleLevelDirectory();

void twoLevelDirectory();

int main() {

int choice;

printf("File Organization Simulation\n");

printf("1. Single Level Directory\n");

printf("2. Two Level Directory\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {
case 1:

singleLevelDirectory();

break;

case 2:

twoLevelDirectory();

break;

default:

printf("Invalid choice!\n");

return 0;

// ---------------------- Single Level Directory ----------------------

void singleLevelDirectory() {

File files[MAX];

int fileCount = 0;

int choice;

char name[50];

while (1) {

printf("\nSingle Level Directory Menu:\n");

printf("1. Create File\n2. Delete File\n3. Search File\n4. List Files\n5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter file name to create: ");

scanf("%s", name);

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

if (strcmp(files[i].filename, name) == 0) {
printf("File already exists!\n");

goto skip;

strcpy(files[fileCount].filename, name);

fileCount++;

printf("File created successfully.\n");

break;

case 2:

printf("Enter file name to delete: ");

scanf("%s", name);

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

if (strcmp(files[i].filename, name) == 0) {

for (int j = i; j < fileCount - 1; j++) {

files[j] = files[j + 1];

fileCount--;

printf("File deleted successfully.\n");

goto skip;

printf("File not found!\n");

break;

case 3:

printf("Enter file name to search: ");

scanf("%s", name);

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

if (strcmp(files[i].filename, name) == 0) {

printf("File found.\n");
goto skip;

printf("File not found!\n");

break;

case 4:

printf("Files in directory:\n");

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

printf("%s\n", files[i].filename);

break;

case 5:

return;

default:

printf("Invalid choice!\n");

skip:;

// ---------------------- Two Level Directory ----------------------

void twoLevelDirectory() {

UserDirectory users[MAX];

int userCount = 0;

int choice;

char uname[50], fname[50];

while (1) {

printf("\nTwo Level Directory Menu:\n");

printf("1. Create User\n2. Create File\n3. Delete File\n4. Search File\n5. List Files\n6. Exit\n");

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter user name: ");

scanf("%s", uname);

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

if (strcmp(users[i].username, uname) == 0) {

printf("User already exists!\n");

goto skip;

strcpy(users[userCount].username, uname);

users[userCount].fileCount = 0;

userCount++;

printf("User created successfully.\n");

break;

case 2:

printf("Enter user name: ");

scanf("%s", uname);

printf("Enter file name to create: ");

scanf("%s", fname);

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

if (strcmp(users[i].username, uname) == 0) {

for (int j = 0; j < users[i].fileCount; j++) {

if (strcmp(users[i].files[j].filename, fname) == 0) {

printf("File already exists!\n");

goto skip;

}
}

strcpy(users[i].files[users[i].fileCount].filename, fname);

users[i].fileCount++;

printf("File created successfully.\n");

goto skip;

printf("User not found!\n");

break;

case 3:

printf("Enter user name: ");

scanf("%s", uname);

printf("Enter file name to delete: ");

scanf("%s", fname);

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

if (strcmp(users[i].username, uname) == 0) {

for (int j = 0; j < users[i].fileCount; j++) {

if (strcmp(users[i].files[j].filename, fname) == 0) {

for (int k = j; k < users[i].fileCount - 1; k++) {

users[i].files[k] = users[i].files[k + 1];

users[i].fileCount--;

printf("File deleted successfully.\n");

goto skip;

printf("File not found!\n");

goto skip;
}

printf("User not found!\n");

break;

case 4:

printf("Enter user name: ");

scanf("%s", uname);

printf("Enter file name to search: ");

scanf("%s", fname);

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

if (strcmp(users[i].username, uname) == 0) {

for (int j = 0; j < users[i].fileCount; j++) {

if (strcmp(users[i].files[j].filename, fname) == 0) {

printf("File found.\n");

goto skip;

printf("File not found!\n");

goto skip;

printf("User not found!\n");

break;

case 5:

printf("Enter user name: ");

scanf("%s", uname);

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

if (strcmp(users[i].username, uname) == 0) {
printf("Files for user %s:\n", uname);

for (int j = 0; j < users[i].fileCount; j++) {

printf("%s\n", users[i].files[j].filename);

goto skip;

printf("User not found!\n");

break;

case 6:

return;

default:

printf("Invalid choice!\n");

skip:;

Experiment No.-11

Write a program to simulate the following file allocation strategies. A) Sequencial b) Indexed

Description :

These strategies determine how files are stored on disk blocks.

Program :

#include <stdio.h>

#include <stdlib.h>

#include <string.h>
#define MAX_BLOCKS 100

int disk[MAX_BLOCKS]; // 0 = free, 1 = allocated

typedef struct {

char name[20];

int start;

int length;

} SequentialFile;

typedef struct {

char name[20];

int indexBlock;

int blocks[20]; // supports up to 20 blocks per file

int length;

} IndexedFile;

void sequentialAllocation();

void indexedAllocation();

int main() {

int choice;

printf("File Allocation Strategy Simulation\n");

printf("1. Sequential Allocation\n2. Indexed Allocation\n");

printf("Enter your choice: ");

scanf("%d", &choice);

// Initialize disk blocks

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

disk[i] = 0;

switch (choice) {

case 1:
sequentialAllocation();

break;

case 2:

indexedAllocation();

break;

default:

printf("Invalid choice.\n");

return 0;

// ------------------- Sequential Allocation -------------------

void sequentialAllocation() {

SequentialFile files[20];

int fileCount = 0, choice;

while (1) {

printf("\nSequential Allocation Menu:\n");

printf("1. Create File\n2. Show Files\n3. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

if (choice == 1) {

SequentialFile f;

printf("Enter file name: ");

scanf("%s", f.name);

printf("Enter starting block: ");

scanf("%d", &f.start);

printf("Enter file length (number of blocks): ");

scanf("%d", &f.length);

int allocated = 1;

if (f.start + f.length > MAX_BLOCKS) {

printf("Error: Out of disk bounds!\n");

continue;
}

for (int i = f.start; i < f.start + f.length; i++) {

if (disk[i] == 1) {

allocated = 0;

break;

if (allocated) {

for (int i = f.start; i < f.start + f.length; i++) {

disk[i] = 1;

files[fileCount++] = f;

printf("File allocated successfully.\n");

} else {

printf("Error: Some blocks already allocated.\n");

} else if (choice == 2) {

printf("Allocated Files:\n");

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

printf("File %s: Start = %d, Length = %d, Blocks = ",

files[i].name, files[i].start, files[i].length);

for (int j = 0; j < files[i].length; j++) {

printf("%d ", files[i].start + j);

printf("\n");

} else if (choice == 3) {

break;

} else {

printf("Invalid choice.\n");

}
}

// ------------------- Indexed Allocation -------------------

void indexedAllocation() {

IndexedFile files[20];

int fileCount = 0, choice;

while (1) {

printf("\nIndexed Allocation Menu:\n");

printf("1. Create File\n2. Show Files\n3. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

if (choice == 1) {

IndexedFile f;

printf("Enter file name: ");

scanf("%s", f.name);

printf("Enter number of blocks required: ");

scanf("%d", &f.length);

// Allocate index block

int indexBlock = -1;

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

if (disk[i] == 0) {

indexBlock = i;

disk[i] = 1;

break;

if (indexBlock == -1) {

printf("No free block available for index block.\n");

continue;

}
f.indexBlock = indexBlock;

int allocatedBlocks = 0;

for (int i = 0; i < MAX_BLOCKS && allocatedBlocks < f.length; i++) {

if (disk[i] == 0) {

f.blocks[allocatedBlocks++] = i;

disk[i] = 1;

if (allocatedBlocks < f.length) {

printf("Not enough space for file. Releasing allocated blocks.\n");

disk[indexBlock] = 0;

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

disk[f.blocks[i]] = 0;

} else {

files[fileCount++] = f;

printf("File allocated with index block %d.\n", f.indexBlock);

} else if (choice == 2) {

printf("Allocated Files:\n");

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

printf("File %s: Index Block = %d, Data Blocks = ",

files[i].name, files[i].indexBlock);

for (int j = 0; j < files[i].length; j++) {

printf("%d ", files[i].blocks[j]);

printf("\n");

} else if (choice == 3) {

break;

} else {

printf("Invalid choice.\n");
}

You might also like