1.
Develop a c program to implement the Process system calls (fork (), exec(), wait(), create
process, terminate process)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // For fork(), exec()
#include <sys/types.h> // For pid_t
#include <sys/wait.h> // For wait()
int main() {
pid_t pid;
// Create a new process using fork()
pid = fork();
if (pid < 0) {
// If fork() fails
perror("Fork failed");
exit(1);
} else if (pid == 0) {
// Child process
printf("Child process created with PID: %d\n", getpid());
// Execute a new program (e.g., using execvp)
char *args[] = {"ls", "-l", NULL}; // Example: list directory contents
execvp(args[0], args);
// If execvp fails
perror("exec failed");
exit(1);
} else {
// Parent process
printf("Parent process with PID: %d waiting for child process to finish...\n", getpid());
// Wait for the child process to terminate
int status;
wait(&status);
if (WIFEXITED(status)) {
printf("Child process terminated with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child process did not terminate successfully\n");
// Parent process continues execution
printf("Parent process completed.\n");
return 0;
2. Simulate the following CPU scheduling algorithms to find turnaround time and waiting time a)
FCFS b) SJF c) Round Robin d) Priority.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int pid;
int burst_time;
int arrival_time;
int priority;
int waiting_time;
int turnaround_time;
int remaining_time; // For Round Robin
} Process;
void calculateTurnaroundTime(Process processes[], int n) {
for (int i = 0; i < n; i++) {
processes[i].turnaround_time = processes[i].waiting_time + processes[i].burst_time;
void calculateWaitingTimeFCFS(Process processes[], int n) {
processes[0].waiting_time = 0;
for (int i = 1; i < n; i++) {
processes[i].waiting_time = processes[i-1].waiting_time + processes[i-1].burst_time;
calculateTurnaroundTime(processes, n);
void calculateWaitingTimeSJF(Process processes[], int n) {
int completed = 0, t = 0, min_burst;
int shortest = 0, finish_time;
int check = 0;
while (completed != n) {
min_burst = 1e9;
check = 0;
for (int j = 0; j < n; j++) {
if (processes[j].arrival_time <= t && processes[j].remaining_time > 0 &&
processes[j].remaining_time < min_burst) {
min_burst = processes[j].remaining_time;
shortest = j;
check = 1;
}
if (check == 0) {
t++;
continue;
t += processes[shortest].remaining_time;
processes[shortest].waiting_time = t - processes[shortest].burst_time -
processes[shortest].arrival_time;
if (processes[shortest].waiting_time < 0)
processes[shortest].waiting_time = 0;
processes[shortest].remaining_time = 0;
completed++;
calculateTurnaroundTime(processes, n);
void calculateWaitingTimePriority(Process processes[], int n) {
int completed = 0, t = 0, highest_priority;
int highest = 0, check = 0;
while (completed != n) {
highest_priority = 1e9;
check = 0;
for (int j = 0; j < n; j++) {
if (processes[j].arrival_time <= t && processes[j].remaining_time > 0 && processes[j].priority <
highest_priority) {
highest_priority = processes[j].priority;
highest = j;
check = 1;
if (check == 0) {
t++;
continue;
t += processes[highest].remaining_time;
processes[highest].waiting_time = t - processes[highest].burst_time -
processes[highest].arrival_time;
if (processes[highest].waiting_time < 0)
processes[highest].waiting_time = 0;
processes[highest].remaining_time = 0;
completed++;
calculateTurnaroundTime(processes, n);
void calculateWaitingTimeRoundRobin(Process processes[], int n, int quantum) {
int t = 0, completed = 0;
while (completed != n) {
int check = 0;
for (int i = 0; i < n; i++) {
if (processes[i].remaining_time > 0) {
check = 1;
if (processes[i].remaining_time > quantum) {
t += quantum;
processes[i].remaining_time -= quantum;
} else {
t += processes[i].remaining_time;
processes[i].waiting_time = t - processes[i].burst_time;
processes[i].remaining_time = 0;
completed++;
if (check == 0)
break;
calculateTurnaroundTime(processes, n);
void printProcesses(Process processes[], int n) {
printf("PID\tBurst Time\tArrival Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].burst_time,
processes[i].arrival_time, processes[i].priority, processes[i].waiting_time,
processes[i].turnaround_time);
}
}
int main() {
int n, quantum;
printf("Enter the number of processes: ");
scanf("%d", &n);
Process processes[n];
for (int i = 0; i < n; i++) {
processes[i].pid = i + 1;
printf("Enter burst time for process %d: ", i + 1);
scanf("%d", &processes[i].burst_time);
printf("Enter arrival time for process %d: ", i + 1);
scanf("%d", &processes[i].arrival_time);
printf("Enter priority for process %d: ", i + 1);
scanf("%d", &processes[i].priority);
processes[i].remaining_time = processes[i].burst_time;
printf("\nFirst Come First Serve (FCFS) Scheduling:\n");
calculateWaitingTimeFCFS(processes, n);
printProcesses(processes, n);
// Reset remaining time for SJF and Priority Scheduling
for (int i = 0; i < n; i++) {
processes[i].remaining_time = processes[i].burst_time;
printf("\nShortest Job First (SJF) Scheduling:\n");
calculateWaitingTimeSJF(processes, n);
printProcesses(processes, n);
// Reset remaining time for Round Robin and Priority Scheduling
for (int i = 0; i < n; i++) {
processes[i].remaining_time = processes[i].burst_time;
printf("\nPriority Scheduling:\n");
calculateWaitingTimePriority(processes, n);
printProcesses(processes, n);
// Reset remaining time for Round Robin Scheduling
for (int i = 0; i < n; i++) {
processes[i].remaining_time = processes[i].burst_time;
printf("\nEnter time quantum for Round Robin Scheduling: ");
scanf("%d", &quantum);
printf("\nRound Robin Scheduling:\n");
calculateWaitingTimeRoundRobin(processes, n, quantum);
printProcesses(processes, n);
return 0;
3. Develop a C program to simulate producer-consumer problem using semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 5 // Define the buffer size
int buffer[BUFFER_SIZE]; // Shared buffer
int in = 0, out = 0; // Variables to track producer and consumer positions
// Semaphores
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
// Function to simulate the producer
void *producer(void *param) {
int item;
while (1) {
item = rand() % 100; // Produce an item
sem_wait(&empty); // Decrement empty count (wait if no empty slots)
pthread_mutex_lock(&mutex); // Enter critical section
// Add the item to the buffer
buffer[in] = item;
printf("Producer produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Exit critical section
sem_post(&full); // Increment full count
sleep(1); // Simulate production time
// Function to simulate the consumer
void *consumer(void *param) {
int item;
while (1) {
sem_wait(&full); // Decrement full count (wait if no items to consume)
pthread_mutex_lock(&mutex); // Enter critical section
// Remove the item from the buffer
item = buffer[out];
printf("Consumer consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Exit critical section
sem_post(&empty); // Increment empty count
sleep(1); // Simulate consumption time
int main() {
pthread_t producer_thread, consumer_thread;
// Initialize semaphores
sem_init(&empty, 0, BUFFER_SIZE); // Initialize 'empty' semaphore with the buffer size
sem_init(&full, 0, 0); // Initialize 'full' semaphore with 0
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
// Create producer and consumer threads
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
// Wait for threads to finish (which they won't in this infinite loop example)
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
// Destroy semaphores and mutex
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
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.
// writer.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define FIFO_NAME "/tmp/myfifo"
int main() {
int fd;
char message[] = "Hello from the writer process!";
// Create the FIFO if it doesn't exist
if (mkfifo(FIFO_NAME, 0666) == -1) {
perror("mkfifo");
exit(1);
// Open the FIFO for writing
fd = open(FIFO_NAME, O_WRONLY);
if (fd == -1) {
perror("open");
exit(1);
// Write the message to the FIFO
if (write(fd, message, strlen(message) + 1) == -1) { // +1 to include the null terminator
perror("write");
exit(1);
printf("Writer: Wrote message to FIFO: %s\n", message);
// Close the FIFO
close(fd);
return 0;
// reader.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "/tmp/myfifo"
#define BUFFER_SIZE 100
int main() {
int fd;
char buffer[BUFFER_SIZE];
// Open the FIFO for reading
fd = open(FIFO_NAME, O_RDONLY);
if (fd == -1) {
perror("open");
exit(1);
// Read the message from the FIFO
if (read(fd, buffer, sizeof(buffer)) == -1) {
perror("read");
exit(1);
printf("Reader: Read message from FIFO: %s\n", buffer);
// Close the FIFO
close(fd);
// Optionally, remove the FIFO file
unlink(FIFO_NAME);
return 0;
5. Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance.
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESSES 5
#define MAX_RESOURCES 3
int main() {
// Initialize the system with some resources and processes
int available[MAX_RESOURCES] = {3, 3, 2}; // Available instances of each resource
int max[MAX_PROCESSES][MAX_RESOURCES] = { // Maximum demand of each process
{7, 5, 3}, // P0
{3, 2, 2}, // P1
{9, 0, 2}, // P2
{2, 2, 2}, // P3
{4, 3, 3} // P4
};
int allocation[MAX_PROCESSES][MAX_RESOURCES] = { // Currently allocated resources to each
process
{0, 1, 0}, // P0
{2, 0, 0}, // P1
{3, 0, 2}, // P2
{2, 1, 1}, // P3
{0, 0, 2} // P4
};
int need[MAX_PROCESSES][MAX_RESOURCES]; // Remaining needs for each process
// Calculate the need matrix (Need = Max - Allocation)
for (int i = 0; i < MAX_PROCESSES; i++) {
for (int j = 0; j < MAX_RESOURCES; j++) {
need[i][j] = max[i][j] - allocation[i][j];
// To track if the process is finished or not
bool finished[MAX_PROCESSES] = {false, false, false, false, false};
int safeSequence[MAX_PROCESSES]; // Safe sequence to store the order of process execution
int work[MAX_RESOURCES]; // Work array to simulate the available resources
// Initially, work = available
for (int i = 0; i < MAX_RESOURCES; i++) {
work[i] = available[i];
int count = 0; // Number of processes that have completed
// Main logic of Banker's algorithm to find the safe sequence
while (count < MAX_PROCESSES) {
bool found = false;
for (int i = 0; i < MAX_PROCESSES; i++) {
if (!finished[i]) {
int j;
for (j = 0; j < MAX_RESOURCES; j++) {
if (need[i][j] > work[j]) {
break;
// If all the resources for the process can be allocated
if (j == MAX_RESOURCES) {
// Simulate allocation
for (int k = 0; k < MAX_RESOURCES; k++) {
work[k] += allocation[i][k];
}
// Add this process to the safe sequence
safeSequence[count++] = i;
// Mark this process as finished
finished[i] = true;
found = true;
// If no process was found in this iteration, there is no safe sequence
if (!found) {
printf("The system is in an unsafe state.\n");
return 0;
// If all processes are finished, we have found a safe sequence
printf("The system is in a safe state.\nSafe sequence is: ");
for (int i = 0; i < MAX_PROCESSES; i++) {
printf("P%d ", safeSequence[i]);
printf("\n");
return 0;
6. Develop a C program to simulate the following contiguous memory allocation Techniques: a)
Worst fit b) Best fit c) First fit.
#include <stdio.h>
#include <stdbool.h>
#define MAX_BLOCKS 10
#define MAX_PROCESSES 10
// Function prototypes
void firstFit(int blockSize[], int blocks, int processSize[], int processes);
void bestFit(int blockSize[], int blocks, int processSize[], int processes);
void worstFit(int blockSize[], int blocks, int processSize[], int processes);
int main() {
int blocks, processes;
// Example memory blocks and processes
int blockSize[MAX_BLOCKS] = {100, 500, 200, 300, 600};
int processSize[MAX_PROCESSES] = {212, 417, 112, 426};
blocks = 5; // Number of memory blocks
processes = 4; // Number of processes
printf("First Fit Memory Allocation:\n");
firstFit(blockSize, blocks, processSize, processes);
// Reset block sizes for next allocation technique
int blockSizeBest[MAX_BLOCKS] = {100, 500, 200, 300, 600};
printf("\nBest Fit Memory Allocation:\n");
bestFit(blockSizeBest, blocks, processSize, processes);
// Reset block sizes for next allocation technique
int blockSizeWorst[MAX_BLOCKS] = {100, 500, 200, 300, 600};
printf("\nWorst Fit Memory Allocation:\n");
worstFit(blockSizeWorst, blocks, processSize, processes);
return 0;
}
// First Fit Memory Allocation
void firstFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX_PROCESSES];
// Initialize allocations to -1 (not allocated)
for (int i = 0; i < processes; i++) {
allocation[i] = -1;
// Allocate memory using First Fit
for (int i = 0; i < processes; i++) {
for (int j = 0; j < blocks; j++) {
if (blockSize[j] >= processSize[i]) {
allocation[i] = j;
blockSize[j] -= processSize[i]; // Reduce available memory in this block
break;
// Print the allocation results
printf("\nProcess No.\tProcess Size\tBlock no.\n");
for (int i = 0; i < processes; i++) {
printf(" %d\t\t%d\t\t", i+1, processSize[i]);
if (allocation[i] != -1) {
printf("%d\n", allocation[i] + 1);
} else {
printf("Not Allocated\n");
}
// Best Fit Memory Allocation
void bestFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX_PROCESSES];
// Initialize allocations to -1 (not allocated)
for (int i = 0; i < processes; i++) {
allocation[i] = -1;
// Allocate memory using Best Fit
for (int i = 0; i < processes; i++) {
int bestIdx = -1;
for (int j = 0; j < blocks; j++) {
if (blockSize[j] >= processSize[i]) {
if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx]) {
bestIdx = j;
// If a block is found
if (bestIdx != -1) {
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i]; // Reduce available memory in this block
}
}
// Print the allocation results
printf("\nProcess No.\tProcess Size\tBlock no.\n");
for (int i = 0; i < processes; i++) {
printf(" %d\t\t%d\t\t", i+1, processSize[i]);
if (allocation[i] != -1) {
printf("%d\n", allocation[i] + 1);
} else {
printf("Not Allocated\n");
// Worst Fit Memory Allocation
void worstFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX_PROCESSES];
// Initialize allocations to -1 (not allocated)
for (int i = 0; i < processes; i++) {
allocation[i] = -1;
// Allocate memory using Worst Fit
for (int i = 0; i < processes; i++) {
int worstIdx = -1;
for (int j = 0; j < blocks; j++) {
if (blockSize[j] >= processSize[i]) {
if (worstIdx == -1 || blockSize[j] > blockSize[worstIdx]) {
worstIdx = j;
// If a block is found
if (worstIdx != -1) {
allocation[i] = worstIdx;
blockSize[worstIdx] -= processSize[i]; // Reduce available memory in this block
// Print the allocation results
printf("\nProcess No.\tProcess Size\tBlock no.\n");
for (int i = 0; i < processes; i++) {
printf(" %d\t\t%d\t\t", i+1, processSize[i]);
if (allocation[i] != -1) {
printf("%d\n", allocation[i] + 1);
} else {
printf("Not Allocated\n");
7. Develop a C program to simulate page replacement algorithms: a) FIFO b) LRU
#include <stdio.h>
#define MAX_FRAMES 10
#define MAX_PAGES 30
// Function prototypes
void fifo(int pages[], int numPages, int frames[], int numFrames);
void lru(int pages[], int numPages, int frames[], int numFrames);
int main() {
int numPages, numFrames;
int pages[MAX_PAGES], frames[MAX_FRAMES];
// Example page reference string
printf("Enter number of pages: ");
scanf("%d", &numPages);
printf("Enter the page reference string: ");
for (int i = 0; i < numPages; i++) {
scanf("%d", &pages[i]);
printf("Enter number of frames: ");
scanf("%d", &numFrames);
// Initialize frames with -1 (indicating empty)
for (int i = 0; i < numFrames; i++) {
frames[i] = -1;
printf("\nFIFO Page Replacement Algorithm:\n");
fifo(pages, numPages, frames, numFrames);
// Reinitialize frames with -1 for LRU simulation
for (int i = 0; i < numFrames; i++) {
frames[i] = -1;
}
printf("\nLRU Page Replacement Algorithm:\n");
lru(pages, numPages, frames, numFrames);
return 0;
// FIFO Page Replacement Algorithm
void fifo(int pages[], int numPages, int frames[], int numFrames) {
int pageFaults = 0;
int index = 0; // To keep track of the oldest page in FIFO
for (int i = 0; i < numPages; i++) {
int page = pages[i];
int found = 0;
// Check if the page is already in one of the frames
for (int j = 0; j < numFrames; j++) {
if (frames[j] == page) {
found = 1;
break;
// If the page is not found in the frames, replace it
if (!found) {
frames[index] = page;
index = (index + 1) % numFrames; // Move to the next frame in a circular manner
pageFaults++;
// Print the current state of frames
printf("Page %d: ", page);
for (int j = 0; j < numFrames; j++) {
if (frames[j] != -1) {
printf("%d ", frames[j]);
} else {
printf("- ");
printf("\n");
printf("Total Page Faults (FIFO): %d\n", pageFaults);
// LRU Page Replacement Algorithm
void lru(int pages[], int numPages, int frames[], int numFrames) {
int pageFaults = 0;
int lruCounter[MAX_FRAMES] = {0}; // To keep track of how recently a page was used
for (int i = 0; i < numPages; i++) {
int page = pages[i];
int found = 0;
// Check if the page is already in one of the frames
for (int j = 0; j < numFrames; j++) {
if (frames[j] == page) {
found = 1;
lruCounter[j] = i; // Update the LRU counter for this page
break;
}
// If the page is not found in the frames, replace it
if (!found) {
int lruIndex = 0;
// Find the least recently used page
for (int j = 1; j < numFrames; j++) {
if (lruCounter[j] < lruCounter[lruIndex]) {
lruIndex = j;
// Replace the least recently used page
frames[lruIndex] = page;
lruCounter[lruIndex] = i; // Update the LRU counter for the new page
pageFaults++;
// Print the current state of frames
printf("Page %d: ", page);
for (int j = 0; j < numFrames; j++) {
if (frames[j] != -1) {
printf("%d ", frames[j]);
} else {
printf("- ");
printf("\n");
}
printf("Total Page Faults (LRU): %d\n", pageFaults);
8. Simulate following File Organization Techniques a) Single level directory b) Two level directory
#include <stdio.h>
#include <string.h>
#define MAX_FILES 100
#define MAX_DIRS 10
#define MAX_FILENAME 100
#define MAX_DIRNAME 100
typedef struct {
char name[MAX_FILENAME];
} File;
typedef struct {
char name[MAX_DIRNAME];
File files[MAX_FILES];
int file_count;
} Directory;
void singleLevelDirectory();
void twoLevelDirectory();
int main() {
int choice;
while (1) {
printf("\nFile Organization Techniques:\n");
printf("1. Single Level Directory\n");
printf("2. Two Level Directory\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
singleLevelDirectory();
break;
case 2:
twoLevelDirectory();
break;
case 3:
return 0;
default:
printf("Invalid choice! Please try again.\n");
return 0;
// Function to simulate Single Level Directory
void singleLevelDirectory() {
File files[MAX_FILES];
int file_count = 0;
int choice;
char filename[MAX_FILENAME];
while (1) {
printf("\nSingle Level Directory:\n");
printf("1. Create File\n");
printf("2. Delete File\n");
printf("3. List Files\n");
printf("4. Go Back\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (file_count < MAX_FILES) {
printf("Enter the filename: ");
scanf("%s", filename);
int exists = 0;
for (int i = 0; i < file_count; i++) {
if (strcmp(files[i].name, filename) == 0) {
exists = 1;
break;
if (!exists) {
strcpy(files[file_count].name, filename);
file_count++;
printf("File '%s' created successfully.\n", filename);
} else {
printf("File '%s' already exists!\n", filename);
} else {
printf("Directory is full! Cannot create more files.\n");
break;
case 2:
printf("Enter the filename to delete: ");
scanf("%s", filename);
int found = 0;
for (int i = 0; i < file_count; i++) {
if (strcmp(files[i].name, filename) == 0) {
for (int j = i; j < file_count - 1; j++) {
files[j] = files[j + 1];
file_count--;
found = 1;
printf("File '%s' deleted successfully.\n", filename);
break;
if (!found) {
printf("File '%s' not found!\n", filename);
break;
case 3:
printf("Files in directory:\n");
for (int i = 0; i < file_count; i++) {
printf("%s\n", files[i].name);
break;
case 4:
return;
default:
printf("Invalid choice! Please try again.\n");
// Function to simulate Two Level Directory
void twoLevelDirectory() {
Directory dirs[MAX_DIRS];
int dir_count = 0;
int choice, dir_index;
char dirname[MAX_DIRNAME], filename[MAX_FILENAME];
while (1) {
printf("\nTwo Level Directory:\n");
printf("1. Create Directory\n");
printf("2. Create File in Directory\n");
printf("3. Delete File from Directory\n");
printf("4. List Files in Directory\n");
printf("5. Go Back\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (dir_count < MAX_DIRS) {
printf("Enter the directory name: ");
scanf("%s", dirname);
int exists = 0;
for (int i = 0; i < dir_count; i++) {
if (strcmp(dirs[i].name, dirname) == 0) {
exists = 1;
break;
if (!exists) {
strcpy(dirs[dir_count].name, dirname);
dirs[dir_count].file_count = 0;
dir_count++;
printf("Directory '%s' created successfully.\n", dirname);
} else {
printf("Directory '%s' already exists!\n", dirname);
}
} else {
printf("Cannot create more directories.\n");
break;
case 2:
printf("Enter the directory name: ");
scanf("%s", dirname);
dir_index = -1;
for (int i = 0; i < dir_count; i++) {
if (strcmp(dirs[i].name, dirname) == 0) {
dir_index = i;
break;
if (dir_index != -1) {
if (dirs[dir_index].file_count < MAX_FILES) {
printf("Enter the filename: ");
scanf("%s", filename);
int exists = 0;
for (int i = 0; i < dirs[dir_index].file_count; i++) {
if (strcmp(dirs[dir_index].files[i].name, filename) == 0) {
exists = 1;
break;
}
}
if (!exists) {
strcpy(dirs[dir_index].files[dirs[dir_index].file_count].name, filename);
dirs[dir_index].file_count++;
printf("File '%s' created in directory '%s'.\n", filename, dirname);
} else {
printf("File '%s' already exists in directory '%s'.\n", filename, dirname);
} else {
printf("Directory is full! Cannot create more files.\n");
} else {
printf("Directory '%s' not found!\n", dirname);
break;
case 3:
printf("Enter the directory name: ");
scanf("%s", dirname);
dir_index = -1;
for (int i = 0; i < dir_count; i++) {
if (strcmp(dirs[i].name, dirname) == 0) {
dir_index = i;
break;
}
if (dir_index != -1) {
printf("Enter the filename to delete: ");
scanf("%s", filename);
int found = 0;
for (int i = 0; i < dirs[dir_index].file_count; i++) {
if (strcmp(dirs[dir_index].files[i].name, filename) == 0) {
for (int j = i; j < dirs[dir_index].file_count - 1; j++) {
dirs[dir_index].files[j] = dirs[dir_index].files[j + 1];
dirs[dir_index].file_count--;
found = 1;
printf("File '%s' deleted from directory '%s'.\n", filename, dirname);
break;
if (!found) {
printf("File '%s' not found in directory '%s'.\n", filename, dirname);
} else {
printf("Directory '%s' not found!\n", dirname);
break;
case 4:
printf("Enter the directory name: ");
scanf("%s", dirname);
dir_index = -1;
for (int i = 0; i < dir_count; i++) {
if (strcmp(dirs[i].name, dirname) == 0) {
dir_index = i;
break;
if (dir_index != -1) {
printf("Files in directory '%s':\n", dirname);
for (int i = 0; i < dirs[dir_index].file_count; i++) {
printf("%s\n", dirs[dir_index].files[i].name);
} else {
printf("Directory '%s' not found!\n", dirname);
break;
case 5:
return;
default:
printf("Invalid choice! Please try again.\n");
9. Develop a C program to simulate the Linked file allocation strategies.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BLOCKS 20
#define MAX_FILES 10
typedef struct Block {
int blockNumber;
int nextBlock;
} Block;
typedef struct File {
int fileID;
int startBlock;
int blockCount;
} File;
void initializeBlocks(Block blocks[], int size);
void allocateFile(File files[], Block blocks[], int fileID, int blockCount);
void deallocateFile(File files[], Block blocks[], int fileID);
void printFileAllocation(File files[], Block blocks[], int fileID);
void listAllFiles(File files[], int fileCount);
int main() {
Block blocks[MAX_BLOCKS];
File files[MAX_FILES];
int fileCount = 0;
int choice, fileID, blockCount;
initializeBlocks(blocks, MAX_BLOCKS);
while (1) {
printf("\nLinked File Allocation Simulation:\n");
printf("1. Allocate File\n");
printf("2. Deallocate File\n");
printf("3. Print File Allocation\n");
printf("4. List All Files\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (fileCount >= MAX_FILES) {
printf("Cannot allocate more files. Maximum limit reached.\n");
break;
printf("Enter file ID: ");
scanf("%d", &fileID);
printf("Enter number of blocks to allocate: ");
scanf("%d", &blockCount);
allocateFile(files, blocks, fileID, blockCount);
fileCount++;
break;
case 2:
printf("Enter file ID to deallocate: ");
scanf("%d", &fileID);
deallocateFile(files, blocks, fileID);
fileCount--;
break;
case 3:
printf("Enter file ID to print allocation: ");
scanf("%d", &fileID);
printFileAllocation(files, blocks, fileID);
break;
case 4:
listAllFiles(files, fileCount);
break;
case 5:
return 0;
default:
printf("Invalid choice! Please try again.\n");
return 0;
// Initialize blocks with no links
void initializeBlocks(Block blocks[], int size) {
for (int i = 0; i < size; i++) {
blocks[i].blockNumber = i;
blocks[i].nextBlock = -1;
}
// Allocate blocks for a file
void allocateFile(File files[], Block blocks[], int fileID, int blockCount) {
int firstFreeBlock = -1;
int lastAllocatedBlock = -1;
int currentBlock = 0;
// Find free blocks and allocate
for (int i = 0; i < MAX_BLOCKS && blockCount > 0; i++) {
if (blocks[i].nextBlock == -1) {
if (firstFreeBlock == -1) {
firstFreeBlock = i;
if (lastAllocatedBlock != -1) {
blocks[lastAllocatedBlock].nextBlock = i;
lastAllocatedBlock = i;
blockCount--;
if (blockCount > 0) {
printf("Not enough free blocks available.\n");
return;
// Save file information
File file;
file.fileID = fileID;
file.startBlock = firstFreeBlock;
file.blockCount = blockCount;
files[fileID] = file;
printf("File %d allocated starting at block %d.\n", fileID, firstFreeBlock);
// Deallocate blocks for a file
void deallocateFile(File files[], Block blocks[], int fileID) {
File file = files[fileID];
int currentBlock = file.startBlock;
int nextBlock;
while (currentBlock != -1) {
nextBlock = blocks[currentBlock].nextBlock;
blocks[currentBlock].nextBlock = -1;
currentBlock = nextBlock;
printf("File %d deallocated.\n", fileID);
// Print file allocation
void printFileAllocation(File files[], Block blocks[], int fileID) {
File file = files[fileID];
int currentBlock = file.startBlock;
printf("File %d is allocated as follows:\n", fileID);
while (currentBlock != -1) {
printf("Block %d -> ", currentBlock);
currentBlock = blocks[currentBlock].nextBlock;
printf("NULL\n");
// List all files
void listAllFiles(File files[], int fileCount) {
printf("Currently allocated files:\n");
for (int i = 0; i < fileCount; i++) {
if (files[i].blockCount > 0) {
printFileAllocation(files, files, i);
10. Develop a C program to simulate SCAN disk scheduling algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_REQUESTS 100
// Function prototypes
void scan(int requests[], int numRequests, int head, int direction, int diskSize);
int main() {
int requests[MAX_REQUESTS];
int numRequests, head, direction, diskSize;
printf("Enter the number of disk requests: ");
scanf("%d", &numRequests);
printf("Enter the disk requests:\n");
for (int i = 0; i < numRequests; i++) {
scanf("%d", &requests[i]);
printf("Enter the current head position: ");
scanf("%d", &head);
printf("Enter the disk size (total number of tracks): ");
scanf("%d", &diskSize);
printf("Enter the direction of head movement (1 for up, 0 for down): ");
scanf("%d", &direction);
scan(requests, numRequests, head, direction, diskSize);
return 0;
// Function to simulate SCAN Disk Scheduling Algorithm
void scan(int requests[], int numRequests, int head, int direction, int diskSize) {
int seekSequence[MAX_REQUESTS + 2];
int distance[MAX_REQUESTS + 2];
int seekCount = 0;
int totalSeekTime = 0;
int start = 0;
// Add head position to the requests array
requests[numRequests] = head;
numRequests++;
// Add disk boundaries to the requests array
requests[numRequests] = 0;
requests[numRequests + 1] = diskSize - 1;
numRequests += 2;
// Sort the requests array
for (int i = 0; i < numRequests - 1; i++) {
for (int j = i + 1; j < numRequests; j++) {
if (requests[i] > requests[j]) {
int temp = requests[i];
requests[i] = requests[j];
requests[j] = temp;
// Find the starting position in the sorted array
for (int i = 0; i < numRequests; i++) {
if (requests[i] == head) {
start = i;
break;
// Start scanning
if (direction == 1) { // Moving up
printf("Seek Sequence: ");
for (int i = start; i < numRequests; i++) {
seekSequence[seekCount++] = requests[i];
if (i != start) {
distance[seekCount - 1] = abs(requests[i] - requests[i - 1]);
totalSeekTime += distance[seekCount - 1];
for (int i = 0; i < start; i++) {
seekSequence[seekCount++] = requests[i];
distance[seekCount - 1] = abs(requests[i] - requests[i - 1]);
totalSeekTime += distance[seekCount - 1];
} else { // Moving down
printf("Seek Sequence: ");
for (int i = start; i >= 0; i--) {
seekSequence[seekCount++] = requests[i];
if (i != start) {
distance[seekCount - 1] = abs(requests[i] - requests[i + 1]);
totalSeekTime += distance[seekCount - 1];
for (int i = numRequests - 1; i > start; i--) {
seekSequence[seekCount++] = requests[i];
distance[seekCount - 1] = abs(requests[i] - requests[i + 1]);
totalSeekTime += distance[seekCount - 1];
// Print the seek sequence and total seek time
for (int i = 0; i < seekCount; i++) {
printf("%d ", seekSequence[i]);
printf("\nTotal Seek Time: %d\n", totalSeekTime);