0% found this document useful (0 votes)
10 views56 pages

Anshulos 1

The document contains multiple C programs demonstrating various process management techniques, including creating child processes, listing directory contents, and implementing scheduling algorithms like FCFS, SJF, and priority scheduling. Each program is accompanied by its source code and a brief description of its functionality. The document serves as a practical guide for understanding process handling and scheduling in operating systems.

Uploaded by

Rajat
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)
10 views56 pages

Anshulos 1

The document contains multiple C programs demonstrating various process management techniques, including creating child processes, listing directory contents, and implementing scheduling algorithms like FCFS, SJF, and priority scheduling. Each program is accompanied by its source code and a brief description of its functionality. The document serves as a practical guide for understanding process handling and scheduling in operating systems.

Uploaded by

Rajat
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/ 56

//Name – Anshul Singh

//Roll No. – 14
//Section – L1
/*1. Write a program to create a child process using system call fork().*/

Source Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
printf("Fork failed!\n");
return 1;
}
else if (pid == 0) {
printf("Child process: pid = %d\n", getpid());
printf("Child's parent process: ppid = %d\n", getppid());
}
else {
printf("Parent process: pid = %d\n", getpid());
printf("Parent's child process: cpid = %d\n", pid);
}
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*2. Write a program to print process Id's of parent and child process i.e. parent should print its own
and its child process id while child process should print its own and its parent process id. (use
getpid(), getppid()).*/

Source Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
printf("\nChild Process:\n");
printf("Child PID = %d\n", getpid());
printf("Parent PID = %d\n", getppid());
}
else if (pid > 0) {
printf("Parent Process:\n");
printf("Parent PID = %d\n", getpid());
printf("Child PID = %d\n", pid);
}
else {
printf("Fork failed!\n");
}
return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*3. Write a program to create child process which will list all the files present in your system. Make
sure that parent process waits until child has not completed its execution. (use wait(), exit())
What will happen if parent process dies before child process? Illustrate it by creating one more
child of parent process.*/

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid1, pid2;

pid1 = fork();

if (pid1 < 0) {
perror("Fork failed");
exit(1);
}
else if (pid1 == 0) {
printf("Child Process (PID: %d) is listing files:\n", getpid());
execlp("ls", "ls", "-l", NULL);
perror("execlp failed");
exit(1);
}
else {
printf("Parent Process (PID: %d) is waiting for the child to complete...\n", getpid());
wait(NULL); // Wait for the child process to complete
printf("Child process has completed.\n");
pid2 = fork();
if (pid2 < 0) {
perror("Fork failed");
exit(1);
}
else if (pid2 == 0) {
printf("Second Child Process (PID: %d) is running...\n", getpid());
sleep(5);
printf("Second Child Process (PID: %d) has completed.\n", getpid());
exit(0);
}
else {
printf("Parent Process (PID: %d) is terminating...\n", getpid());
exit(0);
}
}

return 0;
}
Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*4. Write a program to open a directory and list its contents. (use opendir(), readdir(), closedir() ).*/

Source Code:
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>

int main() {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d == NULL) {
printf("Could not open current directory.\n");
exit(1);
}
printf("Listing directory contents:\n");
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*5. Write a program to show working of execlp() system call by executing ls command.*/

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
printf("Executing ls using execlp()\n");
execlp("ls", "ls", "-l", NULL);
perror("execlp failed");
return 1;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*6. Write a program to read a file and store your details in that file. Your program should also create
one more file and store your friends details in that file. Once both files are created, print lines
which are matching in both files.*/

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100

int main() {
char myDetails[MAX];
char friendDetails[MAX];
char myLines[MAX][MAX], friendLines[MAX][MAX];
int myLineCount = 0, friendLineCount = 0;

printf("Enter your details (e.g., name, age, city): ");


fgets(myDetails, MAX, stdin);
myDetails[strcspn(myDetails, "\n")] = '\0';

printf("Enter your friend's details (e.g., name, age, city): ");


fgets(friendDetails, MAX, stdin);
friendDetails[strcspn(friendDetails, "\n")] = '\0';

FILE *file1 = fopen("file1.txt", "w");


if (file1 == NULL) {
perror("Error opening file");
exit(1);
}
fprintf(file1, "%s\n", myDetails);
fclose(file1);

FILE *file2 = fopen("file2.txt", "w");


if (file2 == NULL) {
perror("Error opening file");
exit(1);
}
fprintf(file2, "%s\n", friendDetails);
fclose(file2);

FILE *readFile1 = fopen("file1.txt", "r");


if (readFile1 == NULL) {
perror("Error opening file");
exit(1);
}
while (fgets(myLines[myLineCount], MAX, readFile1) != NULL) {
myLines[myLineCount][strcspn(myLines[myLineCount], "\n")] = '\0';
myLineCount++;
}
fclose(readFile1);

FILE *readFile2 = fopen("file2.txt", "r");


if (readFile2 == NULL) {
perror("Error opening file");
exit(1);
}
while (fgets(friendLines[friendLineCount], MAX, readFile2) != NULL) {
friendLines[friendLineCount][strcspn(friendLines[friendLineCount], "\n")] = '\0';
friendLineCount++;
}
fclose(readFile2);

printf("\nMatching lines in both files:\n");


for (int i = 0; i < myLineCount; i++) {
for (int j = 0; j < friendLineCount; j++) {
if (strcmp(myLines[i], friendLines[j]) == 0) {
printf("%s\n", myLines[i]);
}
}
}

return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*7. FCFS – First Come First Served : process which arrives first will get the CPU first.*/

Source Code:
#include <stdio.h>
int main() {
int n, i;
int waiting_time[20], turnaround_time[20], burst_time[20], process[20];
float total_waiting_time = 0, total_turnaround_time = 0;
printf("Enter the number of processes (max 20): ");
scanf("%d", &n);
printf("Enter burst time for each process:\n");
for (i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &burst_time[i]);
process[i] = i + 1;
}
waiting_time[0] = 0;
for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
}
for (i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t\t%d\t\t%d\t\t%d\n", process[i], burst_time[i], waiting_time[i], turnaround_time[i]);
}
printf("\nAverage Waiting Time: %.2f\n", total_waiting_time / n);
printf("Average Turnaround Time: %.2f\n", total_turnaround_time / n);
return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*8. SJF NP – Shortest Job First Non-Preemptive : process which needs CPU for least amount will
get the CPU first. Here non-preemptive means currently running process leaves CPU
voultarily after completing its execution*/

Source Code:
#include <stdio.h>
int main() {
int n, burst_time[20], process[20], waiting_time[20], turnaround_time[20], i, j, temp;
float total_waiting_time = 0, total_turnaround_time = 0;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter burst time for each process:\n");
for (i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &burst_time[i]);
process[i] = i + 1;
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (burst_time[i] > burst_time[j]) {
temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;
temp = process[i];
process[i] = process[j];
process[j] = temp;
}
}
}
waiting_time[0] = 0;
for (i = 1; i < n; i++) {
waiting_time[i] = 0;
for (j = 0; j < i; j++) {
waiting_time[i] += burst_time[j];
}
total_waiting_time += waiting_time[i];
}
for (i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
total_turnaround_time += turnaround_time[i];
}
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t\t%d\t\t%d\t\t%d\n", process[i], burst_time[i], waiting_time[i], turnaround_time[i]);
}
printf("\nAverage Waiting Time: %.2f\n", total_waiting_time / n);
printf("Average Turnaround Time: %.2f\n", total_turnaround_time / n);
return 0;
}
Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*9. SJF P – Shortest Job First Preemptive – Here preemptive means operating system decides
when to move currently running process*/

Source Code:
#include <stdio.h>
#define MAX_PROCESSES 100

struct Process {
int pid;
int arrival_time;
int burst_time;
int remaining_time;
int completion_time;
int waiting_time;
int turnaround_time;
int is_completed;
};

void calculateTimes(struct Process p[], int n) {


int time = 0, completed = 0, shortest = -1;
int min_remaining_time = 1e9;
while (completed != n) {
for (int i = 0; i < n; i++) {
if (p[i].arrival_time <= time && !p[i].is_completed && p[i].remaining_time <
min_remaining_time && p[i].remaining_time > 0) {
min_remaining_time = p[i].remaining_time;
shortest = i;
}
}

if (shortest == -1) {
time++;
continue;
}
p[shortest].remaining_time--;
min_remaining_time = p[shortest].remaining_time;
if (p[shortest].remaining_time == 0) {
p[shortest].is_completed = 1;
completed++;
p[shortest].completion_time = time + 1;
p[shortest].turnaround_time = p[shortest].completion_time - p[shortest].arrival_time;
p[shortest].waiting_time = p[shortest].turnaround_time - p[shortest].burst_time;

min_remaining_time = 1e9;
}
time++;
}
}
int main() {
int n;
struct Process p[MAX_PROCESSES];
printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("\nProcess %d:\n", i + 1);
p[i].pid = i + 1;
printf("Arrival Time: ");
scanf("%d", &p[i].arrival_time);
printf("Burst Time: ");
scanf("%d", &p[i].burst_time);
p[i].remaining_time = p[i].burst_time;
p[i].is_completed = 0;
}
calculateTimes(p, n);
printf("\nProcess\tArrival Time\tBurst Time\tCompletion Time\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",
p[i].pid, p[i].arrival_time, p[i].burst_time, p[i].completion_time,
p[i].waiting_time, p[i].turnaround_time);
}
return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*10 .Given a list of processes, their CPU burst times and arrival times, print the Gantt chart for the
following given scheduling policies. Also find averag waiting time and average turnaround time
required for complete execution of these processes.
a) Priority – process which has highest priority will get CPU first.
*/

Source Code:
#include <stdio.h>
struct Process {
int pid;
int burst_time;
int arrival_time;
int priority;
int waiting_time;
int turnaround_time;
};

void calculateTimes(struct Process p[], int n) {


int time = 0;
int total_waiting_time = 0, total_turnaround_time = 0;
printf("\nGantt Chart:\n");
printf("0");
for (int i = 0; i < n; i++) {
time += p[i].burst_time;
printf(" -- P%d -- %d", p[i].pid, time);
p[i].turnaround_time = time - p[i].arrival_time;
p[i].waiting_time = p[i].turnaround_time - p[i].burst_time;
total_waiting_time += p[i].waiting_time;
total_turnaround_time += p[i].turnaround_time;
}
printf("\nAverage Waiting Time: %.2f\n", (float)total_waiting_time / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
}

int main() {
int n;
struct Process process[20];
printf("Enter number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter burst time, arrival time, and priority for process P%d: ", i + 1);
scanf("%d %d %d", &process[i].burst_time, &process[i].arrival_time, &process[i].priority);
process[i].pid = i + 1;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (process[i].priority > process[j].priority) {
struct Process temp = process[i];
process[i] = process[j];
process[j] = temp;
}
}
}
calculateTimes(process, n);
return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*11. Round Robin – each process is provided a fix time to execute. Once a process is executed for
a given time period, it is preempted and other process executes for the given time period.*/

Source Code:
#include <stdio.h>
#define TIME_QUANTUM 2
struct Process {
int pid;
int burst_time;
int arrival_time;
int remaining_time;
int waiting_time;
int turnaround_time;
};

void roundRobin(struct Process p[], int n) {


int time = 0, remaining = n, i;
int total_waiting_time = 0, total_turnaround_time = 0;
printf("\nGantt Chart:\n");
printf("0");
while (remaining > 0) {
for (i = 0; i < n; i++) {
if (p[i].remaining_time > 0 && p[i].arrival_time <= time) {
int time_spent = p[i].remaining_time < TIME_QUANTUM ? p[i].remaining_time :
TIME_QUANTUM;
p[i].remaining_time -= time_spent;
time += time_spent;
printf(" -- P%d -- %d", p[i].pid, time);
if (p[i].remaining_time == 0) {
remaining--;
p[i].turnaround_time = time - p[i].arrival_time;
p[i].waiting_time = p[i].turnaround_time - p[i].burst_time;
total_waiting_time += p[i].waiting_time;
total_turnaround_time += p[i].turnaround_time;
}
}
}
}
printf("\nAverage Waiting Time: %.2f\n", (float)total_waiting_time / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
}

int main() {
int n;
struct Process process[20];
printf("Enter number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter burst time and arrival time for process P%d: ", i + 1);
scanf("%d %d", &process[i].burst_time, &process[i].arrival_time);
process[i].pid = i + 1;
process[i].remaining_time = process[i].burst_time;
}
roundRobin(process, n);

return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*12. Write a C program to simulate multi-level queue scheduling algorithm considering the following
scenario: all the processes in the system are divided into two categories – system processes and
user processes. System processes are to be given higher priority than user processes. Use FCFS
scheduling for the processes in each queue.
*/
Source Code:
#include <stdio.h>
struct Process {
int pid;
int burst_time;
int arrival_time;
int waiting_time;
int turnaround_time;
int is_system_process;
};

void calculateTimes(struct Process p[], int n) {


int total_waiting_time = 0, total_turnaround_time = 0;
int time = 0;
printf("\nGantt Chart:\n");
printf("0");
for (int i = 0; i < n; i++) {
if (time < p[i].arrival_time) {
time = p[i].arrival_time;
}
time += p[i].burst_time;
printf(" -- P%d -- %d", p[i].pid, time);
p[i].turnaround_time = time - p[i].arrival_time;
p[i].waiting_time = p[i].turnaround_time - p[i].burst_time;
total_waiting_time += p[i].waiting_time;
total_turnaround_time += p[i].turnaround_time;
}
printf("\nAverage Waiting Time: %.2f\n", (float)total_waiting_time / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
}
void sortProcessesByArrival(struct Process p[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (p[i].arrival_time > p[j].arrival_time) {
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
void segregateProcesses(struct Process p[], int n, struct Process system_queue[], struct Process
user_queue[], int *sys_count, int *user_count) {
*sys_count = 0;
*user_count = 0;
for (int i = 0; i < n; i++) {
if (p[i].is_system_process) {
system_queue[(*sys_count)++] = p[i];
} else {
user_queue[(*user_count)++] = p[i];
}
}
}

int main() {
int n, i, sys_count = 0, user_count = 0;
struct Process process[20], system_queue[20], user_queue[20];
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter burst time and arrival time for each process:\n");
for (i = 0; i < n; i++) {
printf("Process P%d: ", i + 1);
scanf("%d %d", &process[i].burst_time, &process[i].arrival_time);
process[i].pid = i + 1;
process[i].is_system_process = 0;
}
int m;
printf("Enter the number of system processes: ");
scanf("%d", &m);
printf("Enter the process IDs of system processes: ");
for (i = 0; i < m; i++) {
int sys_pid;
scanf("%d", &sys_pid);
process[sys_pid - 1].is_system_process = 1;
}
segregateProcesses(process, n, system_queue, user_queue, &sys_count, &user_count);
sortProcessesByArrival(system_queue, sys_count);
sortProcessesByArrival(user_queue, user_count);
printf("\nSystem Queue (Higher Priority) Scheduling:\n");
calculateTimes(system_queue, sys_count);
printf("\nUser Queue (Lower Priority) Scheduling:\n");
calculateTimes(user_queue, user_count);
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*13. Write a program to communicate parent and child process with each other in such a way that
whenever child writes something, parent process can read it. Conside mode of communication is through
a) pipe
*/

Source Code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main() {
int pipefd[2];
pid_t pid;
char writeMessage[] = "Message from child to parent via pipe";
char readMessage[100];
if (pipe(pipefd) == -1) {
perror("pipe failed");
return 1;
}
pid = fork();
if (pid < 0) {
perror("Fork failed");
return 1;
}
if (pid == 0) {
close(pipefd[0]);
write(pipefd[1], writeMessage, strlen(writeMessage) + 1);
close(pipefd[1]);
}
else {
close(pipefd[1]);
read(pipefd[0], readMessage, sizeof(readMessage));
printf("Parent received: %s\n", readMessage);
close(pipefd[0]);
}
return 0;
}

Output:

//b) message passing


Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>
#include <string.h>
#define MSG_SIZE 100

struct msg_buffer {
long msg_type;
char msg_text[MSG_SIZE];
};

int main() {
key_t key;
int msgid;
pid_t pid;
struct msg_buffer message;
key = ftok("progfile", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
pid = fork();
if (pid < 0) {
perror("Fork failed");
return 1;
}
if (pid == 0) {
message.msg_type = 1;
strcpy(message.msg_text, "Message from child to parent via message queue");
msgsnd(msgid, &message, sizeof(message), 0);
printf("Child sent: %s\n", message.msg_text);
}
else {
msgrcv(msgid, &message, sizeof(message), 1, 0);
printf("Parent received: %s\n", message.msg_text);
msgctl(msgid, IPC_RMID, NULL);
}
return 0;
}

Output:

//c) shared memory


Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>

int main() {
key_t key = ftok("shmfile", 65);
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char *shared_memory = (char*) shmat(shmid, NULL, 0);
pid_t pid;
pid = fork();
if (pid < 0) {
perror("Fork failed");
return 1;
}
if (pid == 0) {
strcpy(shared_memory, "Message from child to parent via shared memory");
printf("Child wrote: %s\n", shared_memory);
}
else {
printf("Parent read: %s\n", shared_memory);
shmdt(shared_memory);
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*14.Write a program to implement the concept of Producer-Consumer problem using semaphores*/

Source Code:
#include <stdio.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;
for (int i = 0; i < 10; i++) {
item = i + 1;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Producer produced item %d at index %d\n", item, in);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}

void* consumer(void* arg) {


int item;
for (int i = 0; i < 10; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = buffer[out];
printf("Consumer consumed item %d from index %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(2);
}
return NULL;
}

int main() {
pthread_t prod, cons;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}

Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*15. Write a program to implement the concept of Dining-Philosopher problem.*/

Source Code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_PHILOSOPHERS 5
#define MAX_EATS 3
pthread_mutex_t forks[NUM_PHILOSOPHERS];
pthread_t philosophers[NUM_PHILOSOPHERS];
void* philosopher(void* num) {
int id = *(int*)num;
int eats = 0;
while (eats < MAX_EATS) {
printf("Philosopher %d is thinking...\n", id);
sleep(1);
int left = id;
int right = (id + 1) % NUM_PHILOSOPHERS;
if (id % 2 == 0) {
pthread_mutex_lock(&forks[left]);
pthread_mutex_lock(&forks[right]);
} else {
pthread_mutex_lock(&forks[right]);
pthread_mutex_lock(&forks[left]);
}
printf("Philosopher %d is eating...\n", id);
sleep(2);
eats++;
pthread_mutex_unlock(&forks[left]);
pthread_mutex_unlock(&forks[right]);
printf("Philosopher %d finished eating and is thinking again.\n", id);
}
printf("Philosopher %d has finished eating.\n", id);
return NULL;
}
int main() {
int ids[NUM_PHILOSOPHERS];
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
pthread_mutex_init(&forks[i], NULL);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
ids[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &ids[i]);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
pthread_join(philosophers[i], NULL);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
pthread_mutex_destroy(&forks[i]);
}
return 0;
}
Output:

//Name – Anshul Singh


//Roll No. – 14
//Section – L1
/*16. Write a C program to simulate Bankers algorithm for the purpose of deadlock avoidance..*/

Source Code:
#include <stdio.h>
#include <stdbool.h>
void calculateNeed(int need[][10], int max[][10], int alloc[][10], int p, int r) {
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
}
}

bool isSafe(int processes[], int avail[], int max[][10], int alloc[][10], int p, int r) {
int need[10][10];
calculateNeed(need, max, alloc, p, r);
bool finish[10] = {0};
int safeSeq[10];
int work[10];
for (int i = 0; i < r; i++) {
work[i] = avail[i];
}
int count = 0;
while (count < p) {
bool found = false;

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


if (!finish[i]) {
bool flag = true;
for (int j = 0; j < r; j++) {
if (need[i][j] > work[j]) {
flag = false;
break;
}
}
if (flag) {
for (int k = 0; k < r; k++) {
work[k] += alloc[i][k];
}
safeSeq[count++] = i;
finish[i] = 1;
found = true;
}
}
}
if (!found) {
printf("Request cannot be fulfilled\n");
return false;
}
}
printf("Request can be fulfilled\n");
printf("Safe sequence is: ");
for (int i = 0; i < p; i++) {
printf("P%d ", safeSeq[i]);
}
printf("\n");
return true;
}
int main() {
int p, r;
int processes[10];
int max[10][10], alloc[10][10], avail[10];
printf("Enter the number of processes: ");
scanf("%d", &p);
printf("Enter the number of resources: ");
scanf("%d", &r);
printf("Enter the maximum requirement matrix:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the allocation matrix:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
scanf("%d", &alloc[i][j]);
}
}
printf("Enter the resource vector (total resources available before allocation):\n");
for (int i = 0; i < r; i++) {
scanf("%d", &avail[i]);
}
for (int i = 0; i < p; i++) {
processes[i] = i;
}
isSafe(processes, avail, max, alloc, p, r);
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*17. Write a program to implement deadlock detection algorithm.*/

Source Code:
#include <stdio.h>
#define MAX 100
int main() {
int p, r, i, j;
int max[MAX][MAX], allocation[MAX][MAX], need[MAX][MAX];
int available[MAX], work[MAX], finish[MAX] = {0};
int deadlockDetected = 0;
printf("Enter the no. of processes = ");
scanf("%d", &p);
printf("Enter the no. of resources = ");
scanf("%d", &r);
printf("Enter maximum requirement :\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter allocated matrix :\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &allocation[i][j]);
}
}
printf("Resource vector = ");
for (i = 0; i < r; i++) {
scanf("%d", &available[i]);
}
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
for (i = 0; i < r; i++) {
work[i] = available[i];
}
while (1) {
int progress = 0;
for (i = 0; i < p; i++) {
if (!finish[i]) {
int canProceed = 1;

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


if (need[i][j] > work[j]) {
canProceed = 0;
break;
}
}
if (canProceed) {
for (j = 0; j < r; j++) {
work[j] += allocation[i][j];
}
finish[i] = 1;
progress = 1;
}
}
}
if (!progress) {
break;
}
}
for (i = 0; i < p; i++) {
if (!finish[i]) {
deadlockDetected = 1;
break;
}
}
if (deadlockDetected) {
printf("Deadlock detected\n");
} else {
printf("No deadlock detected\n");
}
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*18. Write a program to implement FIFO.*/

Source Code:
#include <stdio.h>
int main() {
int frames, n;
printf("Please enter the number of frames: ");
scanf("%d", &frames);
printf("Please enter the number of page requests: ");
scanf("%d", &n);
int requests[n];
int memory[frames];
int page_faults = 0;
int i, j, found;
for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
for (i = 0; i < frames; i++) {
memory[i] = -1;
}
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < frames; j++) {
if (memory[j] == requests[i]) {
found = 1;
break;
}
}
if (!found) {
page_faults++;
for (j = 0; j < frames; j++) {
if (memory[j] == -1) {
memory[j] = requests[i];
break;
}
}
if (j == frames) {
for (j = 0; j < frames - 1; j++) {
memory[j] = memory[j + 1];
}
memory[frames - 1] = requests[i];
}
}
}
printf("Total number of page faults: %d\n", page_faults);
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*19. Write a program to implement LRU.*/

Source Code:
#include <stdio.h>
int main() {
int frames, n;
printf("Please enter the number of frames: ");
scanf("%d", &frames);
printf("Please enter the number of page requests: ");
scanf("%d", &n);
int requests[n];
int memory[frames];
int page_faults = 0;
int i, j, found, least_recent, least_recent_index;
for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
for (i = 0; i < frames; i++) {
memory[i] = -1;
}
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < frames; j++) {
if (memory[j] == requests[i]) {
found = 1;
break;
}
}
if (!found) {
page_faults++;
for (j = 0; j < frames; j++) {
if (memory[j] == -1) {
memory[j] = requests[i];
break;
}
}
if (j == frames) {
least_recent = -1;
least_recent_index = -1;
for (j = 0; j < frames; j++) {
int k;
for (k = i - 1; k >= 0; k--) {
if (requests[k] == memory[j]) {
if (k < least_recent || least_recent == -1) {
least_recent = k;
least_recent_index = j;
}
break;
}
}
if (k == -1) {
least_recent_index = j;
break;
}
}
memory[least_recent_index] = requests[i];
}
}
}
printf("Total number of page faults: %d\n", page_faults);
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*20. Write a program to implement Best Fit.*/

Source Code:
#include <stdio.h>
int main() {
int b, p;
printf("Please enter the number of blocks: ");
scanf("%d", &b);
int blocks[b];
for (int i = 0; i < b; i++) {
scanf("%d", &blocks[i]);
}
printf("Please enter the number of processes: ");
scanf("%d", &p);
int processes[p];
for (int i = 0; i < p; i++) {
scanf("%d", &processes[i]);
}
int allocation[p];
for (int i = 0; i < p; i++) allocation[i] = -1;
for (int i = 0; i < p; i++) {
int best_fit_index = -1;
int best_fit_size = 1000000;
for (int j = 0; j < b; j++) {
if (blocks[j] >= processes[i] && blocks[j] < best_fit_size) {
best_fit_size = blocks[j];
best_fit_index = j;
}
}
if (best_fit_index != -1) {
allocation[i] = best_fit_index;
blocks[best_fit_index] = -1;
} else {
allocation[i] = -1;
}
}
printf("\n");
for (int i = 0; i < p; i++) {
if (allocation[i] != -1) {
printf("%d-%d\n", processes[i], allocation[i] + 1);
} else {
printf("Process %d: no free block available\n", i + 1);
}
}
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*21. Write a program to implement First Fit.*/

Source Code:
#include <stdio.h>
int main() {
int b, p;
printf("Please enter the number of blocks: ");
scanf("%d", &b);
int blocks[b];
for (int i = 0; i < b; i++) {
scanf("%d", &blocks[i]);
}
printf("Please enter the number of processes: ");
scanf("%d", &p);
int processes[p];
for (int i = 0; i < p; i++) {
scanf("%d", &processes[i]);
}
int allocation[p];
for (int i = 0; i < p; i++) {
allocation[i] = -1;
}
for (int i = 0; i < p; i++) {
int allocated = 0;
for (int j = 0; j < b; j++) {
if (blocks[j] >= processes[i]) {
allocation[i] = j;
blocks[j] -= processes[i];
allocated = 1;
break;
}
}
if (!allocated) {
allocation[i] = -1;
}
}
printf("\n");
for (int i = 0; i < p; i++) {
if (allocation[i] != -1) {
printf("%d-%d\n", processes[i], allocation[i] + 1);
} else {
printf("Process %d: no free block available\n", i + 1);
}
}
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*22. Write a program to implement Worst Fit.*/

Source Code:
#include <stdio.h>
int main() {
int b, p;
printf("Please enter the number of blocks: ");
scanf("%d", &b);
int blocks[b];
for (int i = 0; i < b; i++) {
scanf("%d", &blocks[i]);
}
printf("Please enter the number of processes: ");
scanf("%d", &p);
int processes[p];
for (int i = 0; i < p; i++) {
scanf("%d", &processes[i]);
}
int allocation[p];
for (int i = 0; i < p; i++) {
allocation[i] = -1;
}
for (int i = 0; i < p; i++) {
int worst_fit_index = -1;
int worst_fit_size = -1;

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


if (blocks[j] >= processes[i] && blocks[j] > worst_fit_size) {
worst_fit_size = blocks[j];
worst_fit_index = j;
}
}
if (worst_fit_index != -1) {
allocation[i] = worst_fit_index;
blocks[worst_fit_index] -= processes[i];
} else {
allocation[i] = -1;
}
}
printf("\n");
for (int i = 0; i < p; i++) {
if (allocation[i] != -1) {
printf("%d-%d\n", processes[i], allocation[i] + 1);
} else {
printf("Process %d: no free block available\n", i + 1);
}
}
}
Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*23. Write a program to implement Sequential/Contiguous File Allocation.*/

Source Code:
#include <stdio.h>
#include <string.h>
#define MAX_FILES 100
struct File {
char name[50];
int starting_block;
int num_blocks;
};
int main() {
int F;
struct File files[MAX_FILES];
int i, j;
char search_file[50];
printf("Enter number of files: ");
scanf("%d", &F);
for (i = 0; i < F; i++) {
printf("Enter file %d name: ", i + 1);
scanf("%s", files[i].name);
printf("Enter starting block of file %d: ", i + 1);
scanf("%d", &files[i].starting_block);
printf("Enter number of blocks in file %d: ", i + 1);
scanf("%d", &files[i].num_blocks);
}
printf("Enter the file name to search: ");
scanf("%s", search_file);
int found = 0;
for (i = 0; i < F; i++) {
if (strcmp(files[i].name, search_file) == 0) {
printf("\nFile Name\tStart Block\tNo. of Blocks\tBlocks Occupied\n");
printf("%s\t\t%d\t\t%d\t\t", files[i].name, files[i].starting_block, files[i].num_blocks);
for (j = files[i].starting_block; j < files[i].starting_block + files[i].num_blocks; j++) {
if (j == files[i].starting_block + files[i].num_blocks - 1) {
printf("%d", j);
} else {
printf("%d, ", j);
}
}
printf("\n");
found = 1;
break;
}
}
if (!found) printf("File not found.\n");
return 0;
}
Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*24. Write a program to implement Linked File Allocation.*/

Source Code:
#include <stdio.h>
#include <string.h>
#define MAX_FILES 100
#define MAX_BLOCKS 1000
struct File {
char name[50];
int starting_block;
int num_blocks;
int blocks[MAX_BLOCKS];
};
int main() {
int F;
struct File files[MAX_FILES];
int i, j;
char search_file[50];
printf("Enter number of files: ");
scanf("%d", &F);
for (i = 0; i < F; i++) {
printf("Enter file %d name: ", i + 1);
scanf("%s", files[i].name);
printf("Enter starting block of file %d: ", i + 1);
scanf("%d", &files[i].starting_block);
printf("Enter number of blocks in file %d: ", i + 1);
scanf("%d", &files[i].num_blocks);
printf("Enter blocks for file %d: ", i + 1);
for (j = 0; j < files[i].num_blocks; j++) {
scanf("%d", &files[i].blocks[j]);
}
}
printf("Enter the file name to search: ");
scanf("%s", search_file);
int found = 0;
for (i = 0; i < F; i++) {
if (strcmp(files[i].name, search_file) == 0) {
printf("\nFile Name\tStart Block\tNo. of Blocks\tBlocks Occupied\n");
printf("%s\t\t%d\t\t%d\t\t", files[i].name, files[i].starting_block, files[i].num_blocks);
for (j = 0; j < files[i].num_blocks; j++) {
if (j == files[i].num_blocks - 1) printf("%d", files[i].blocks[j]);
else printf("%d, ", files[i].blocks[j]);
}printf("\n");
found = 1;
break;
}}
if (!found) printf("File not found.\n");
}
Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*25. Write a program to implement Indexed File Allocation.*/

Source Code:
#include <stdio.h>
#include <string.h>
#define MAX_FILES 100
#define MAX_BLOCKS 1000
struct File {
char name[50];
int index_block;
int num_blocks;
int data_blocks[MAX_BLOCKS];
};
int main() {
int F, i, j;
struct File files[MAX_FILES];
char search_file[50];
printf("Enter number of files: ");
scanf("%d", &F);
for (i = 0; i < F; i++) {
printf("Enter file %d name: ", i + 1);
scanf("%s", files[i].name);
printf("Enter index block of file %d: ", i + 1);
scanf("%d", &files[i].index_block);
printf("Enter number of blocks in file %d: ", i + 1);
scanf("%d", &files[i].num_blocks);
printf("Enter blocks for file %d: ", i + 1);
for (j = 0; j < files[i].num_blocks; j++) {
scanf("%d", &files[i].data_blocks[j]);
}
}
printf("Enter the file name to search: ");
scanf("%s", search_file);
int found = 0;
for (i = 0; i < F; i++) {
if (strcmp(files[i].name, search_file) == 0) {
printf("\nFile Name\tIndex Block\tNo. of Blocks\tBlocks Occupied\n");
printf("%s\t\t%d\t\t%d\t\t", files[i].name, files[i].index_block, files[i].num_blocks);
for (j = 0; j < files[i].num_blocks; j++) {
if (j == files[i].num_blocks - 1) printf("%d", files[i].data_blocks[j]);
else printf("%d, ", files[i].data_blocks[j]);
}
printf("\n");
found = 1;
break;
}}
if (!found) printf("File not found.\n");
}
Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*26. Write a program to implement FCFS Disc Sheduling.*/

Source Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n,i,total_seek=0,current_position=55;
printf("Enter number of disk requests: ");
scanf("%d",&n);
int tracks[n];
for(i=0;i<n;i++) {
scanf("%d",&tracks[i]);
}
for(i=0;i<n;i++) {
total_seek+=abs(tracks[i]-current_position);
current_position=tracks[i];
}
printf("Total seek movement: %d\n",total_seek);
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*27. Write a program to implement SCAN Disc Sheduling.*/

Source Code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int n, i, total_seek = 0, current_position = 57, max_track = 200;
printf("Enter number of disk requests: ");
scanf("%d", &n);
int tracks[n];
printf("Enter the track numbers: ");
for (i = 0; i < n; i++) {
scanf("%d", &tracks[i]);
}
for (i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (tracks[i] > tracks[j]) {
int temp = tracks[i];
tracks[i] = tracks[j];
tracks[j] = temp;
}
}
}
int left[n], right[n], left_count = 0, right_count = 0;
for (i = 0; i < n; i++) {
if (tracks[i] < current_position) {
left[left_count++] = tracks[i];
} else {
right[right_count++] = tracks[i];
}
}
for (i = 0; i < right_count; i++) {
total_seek += abs(current_position - right[i]);
current_position = right[i];
}
if (right_count > 0 && current_position < max_track) {
total_seek += abs(max_track - current_position);
current_position = max_track;
}
for (i = left_count - 1; i >= 0; i--) {
total_seek += abs(current_position - left[i]);
current_position = left[i];
}
printf("Total seek movement: %d\n", total_seek);
return 0;
}

Output:
//Name – Anshul Singh
//Roll No. – 14
//Section – L1
/*28. Write a program to implement C-SCAN Disc Sheduling.*/

Source Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, total_seek = 0, current_position = 85, max_track = 200;
printf("Enter number of disk requests: ");
scanf("%d", &n);
int tracks[n];
printf("Enter the track numbers: ");
for (i = 0; i < n; i++) {
scanf("%d", &tracks[i]);
}
for (i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (tracks[i] > tracks[j]) {
int temp = tracks[i];
tracks[i] = tracks[j];
tracks[j] = temp;
}
}
}
int left[n], right[n], left_count = 0, right_count = 0;
for (i = 0; i < n; i++) {
if (tracks[i] < current_position) {
left[left_count++] = tracks[i];
} else {
right[right_count++] = tracks[i];
}
}
for (i = 0; i < right_count; i++) {
total_seek += abs(current_position - right[i]);
current_position = right[i];
}
total_seek += abs(max_track - current_position);
current_position = 0;
for (i = left_count - 1; i >= 0; i--) {
total_seek += abs(current_position - left[i]);
current_position = left[i];
}
printf("Total seek movement: %d\n", total_seek);
return 0;
}

Output:

You might also like