OS Lab Manual
OS Lab Manual
Sem:3rd Dr Ganesha M
1. Develop a c program to implement the Process system calls (fork (), exec(), wait(),
createprocess,terminate process)
a. Single process
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t child_pid;
int status;
// Create a child process
child_pid = fork();
if (child_pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (child_pid == 0) {
// Child process
printf("Child process (PID: %d) is running.\n", getpid());
// Replace the child process with a new program
execlp("/bin/ls", "ls", "-l", NULL);
// If exec fails, the code below will be executed
perror("Exec failed");
exit(1);
1
} else {
// Parent process
printf("Parent process (PID: %d) created a child (PID: %d).\n", getpid(), child_pid);
// Wait for the child process to finish
wait(&status);
if (WIFEXITED(status)) {
printf("Child process (PID: %d) exited with status %d.\n", child_pid,
WEXITSTATUS(status));
} else {
printf("Child process (PID: %d) did not exit normally.\n", child_pid);
}
}
return 0;
}
b. Multiple processes
// C program to demonstrate waitpid()
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
void waitexample()
{
int i, stat;
pid_t pid[5];
for (i=0; i<5; i++)
{
if ((pid[i] = fork()) == 0)
{
2
sleep(1);
exit(100 + i);
}
}
// Using waitpid() and printing exit status of children.
3
2)Simulate the following CPU scheduling algorithms to find turnaround time and waiting time
a)FCFS
b) SJF
c) Round Robin
d) Priority.
c. FCFS
#include <stdio.h>
struct Process {
int pid; // Process ID
int arrival; // Arrival time
int burst; // Burst time
};
4
currentTime += processes[i].burst;
}
int main() {
struct Process processes[] = {
{1, 0, 6},
{2, 2, 3},
{3, 3, 8}
};
fcfsScheduling(processes, n);
return 0;
}
5
d. SJF
#include <stdio.h>
struct Process {
int pid; // Process ID
int burst; // Burst time
};
6
for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
printf("%d\t%d\t\t%d\t\t%d\n", proc[i].pid, proc[i].burst, wt[i], tat[i]);
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
7
struct Process proc[n];
sortProcesses(proc, n);
findAverageTime(proc, n);
return 0;
}
8
e. Round Robin
#include <stdio.h>
struct Process {
int pid; // Process ID
int burst; // Burst time
};
while (1) {
int allDone = 1; // Flag to check if all processes are completed
9
printf("Process %d executed for remaining time %d\n", processes[i].pid, remaining[i]);
}
}
}
if (allDone)
break;
}
}
int main() {
struct Process processes[] = {
{1, 10},
{2, 5},
{3, 8},
{4, 12}
};
roundRobinScheduling(processes, n, timeQuantum);
return 0;
}
10
f. Priority Scheduling
/******************************************************************************
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
// Process structure
typedef struct Process {
int id; // Process ID
int priority; // Priority of the process (lower value indicates higher priority)
int burst_time; // Burst time (time required to complete the process)
} Process;
11
printf("Enter burst time for Process %d: ", i);
scanf("%d", &processes[i].burst_time);
}
}
int total_time = 0;
double average_waiting_time = 0.0;
total_time += processes[i].burst_time;
average_waiting_time += total_time;
12
// Waiting time for the next process (waiting time = total time so far)
average_waiting_time += total_time;
}
average_waiting_time /= num_processes;
int main() {
int num_processes;
Process processes[MAX_PROCESSES];
initializeProcesses(processes, num_processes);
priorityScheduling(processes, num_processes);
return 0;
}
13
2. Develop a C program to simulate producer-consumer problem using semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 20
while (1) {
sem_wait(&empty);
buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
item++;
sem_post(&full);
if(item>size){
break;
}
14
}
printf("Sending completed\n ");
pthread_exit(NULL);
}
while (1) {
sem_wait(&full);
item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
sem_post(&empty);
if(item==size){
printf("Received all");
break;
}
}
pthread_exit(NULL);
}
int main() {
pthread_t producer_thread, consumer_thread;
15
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
16
3. Develop a C program which demonstrates interprocess communication between a reader
process and a writer process. Use mkfifo, open, read, write and close APIs in your program.
A Write First
// C program to implement one side of FIFO
int main()
{
int fd;
17
// Take an input arr2ing from user.
// 80 is maximum length
fgets(arr2, 80, stdin);
18
b. Read First
// C program to implement one side of FIFO
// This side reads first, then reads
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd1;
19
printf("User1: %s\n", str1);
close(fd1);
20
4. Develop a C program to simulate Bankers Algorithm for Deadlock Avoidance..
a. Single process allotment
#include <stdio.h>
#include <stdbool.h>
// Available resources
int available[NUM_RESOURCES] = {3, 3, 2};
21
// Need resources for each process
int need[NUM_PROCESSES][NUM_RESOURCES];
22
}
}
int main() {
calculateNeedMatrix();
int requestProcess = 1;
int request[NUM_RESOURCES] = {1, 2, 2};
if (canGrantResources(requestProcess, request)) {
allocateResources(requestProcess, request);
printf("Resources granted to process %d.\n", requestProcess);
printf("Updated allocation matrix:\n");
for (int i = 0; i < NUM_PROCESSES; i++) {
for (int j = 0; j < NUM_RESOURCES; j++) {
printf("%d ", allocation[i][j]);
}
printf("\n");
}
} else {
printf("Resources cannot be granted to process %d.\n", requestProcess);
}
return 0;
}
23
b. Multiple process allottment
// Banker's Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
int avail[3] = { 3, 3, 2 }; // Available Resources
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
24
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
25
}
}
if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}
return (0);
// This code is contributed by Deep Baldha (CandyZack)
}
26
5. Develop a C program to simulate the following contiguous memory allocation Techniques:
a) Worst fit b) Best fit c) First fit.
a. Worst fit
#include <stdio.h>
if (worstIdx != -1) {
27
// Allocate the memory block
blocks[worstIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, worstIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}
}
int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
28
scanf("%d", &processSize);
worstFit(blocks, m, processSize);
}
return 0;
}
b. Best fit
#include <stdio.h>
29
}
}
if (bestIdx != -1) {
// Allocate the memory block
blocks[bestIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, bestIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}
}
int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
30
for (int i = 0; i < n; i++) {
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
bestFit(blocks, m, processSize);
}
return 0;
}
// Number of processes
#define NUM_PROCESSES 5
// Sizes of processes
int process_sizes[NUM_PROCESSES] = {212, 417, 112, 426, 112};
31
// Function to perform Best Fit memory allocation
void bestFit() {
for (int i = 0; i < NUM_PROCESSES; i++) {
int best_fit_index = -1;
for (int j = 0; j < NUM_BLOCKS; j++) {
if (!allocated[j] && memory_blocks[j] >= process_sizes[i]) {
if (best_fit_index == -1 || memory_blocks[j] < memory_blocks[best_fit_index]) {
best_fit_index = j;
}
}
}
if (best_fit_index != -1) {
allocated[best_fit_index] = 1;
printf("Process %d (size %d) is allocated to Block %d (size %d)\n",
i, process_sizes[i], best_fit_index, memory_blocks[best_fit_index]);
} else {
printf("Process %d (size %d) cannot be allocated\n", i, process_sizes[i]);
}
}
}
int main() {
bestFit();
return 0;
}
32
c. First fit
#include <stdio.h>
int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
33
scanf("%d", &m);
return 0;
}
34
6. Develop a C program to simulate page replacement algorithms:
a) FIFO b) LRU
a. FIFO
#include <stdio.h>
int main()
{
int incomingStream[] = {4 , 1 , 2 , 4 , 5,4,1,2,3,6};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;
pages = sizeof(incomingStream)/sizeof(incomingStream[0]);
printf(" Incoming \t Frame 1 \t Frame 2 \t Frame 3 ");
int temp[ frames ];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}
35
pageFaults++;
if((pageFaults <= frames) && (s == 0))
{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}
printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}
36
b. LRU
#include<stdio.h>
#include<limits.h>
return 0;
}
int main()
{
int n = sizeof(incomingStream)/sizeof(incomingStream[0]);
int frames = 3;
37
int queue[n];
int distance[n];
int occupied = 0;
int pagefault = 0;
printFrame(queue, occupied);
}
else{
38
int index;
// get LRU distance for each item in frame
for (int j = 0; j < frames; j++)
{
distance[j] = 0;
// traverse in reverse direction to find
// at what distance frame item occurred last
for(int k = i - 1; k >= 0; k--)
{
++distance[j];
if(queue[j] == incomingStream[k])
break;
}
printf("\n");
39
}
return 0;
}
40
7. Simulate following File Organization Techniques:
a) Single level directory
b)Two level directory
41
File newFile;
strncpy(newFile.name, name, MAX_NAME_LENGTH);
newFile.size = size;
strncpy(newFile.content, content, sizeof(newFile.content));
return newFile;
}
int main() {
Directory directory;
directory.num_files = 0;
42
// Create and add files to the directory
File file1 = createFile("File1.txt", 100, "This is the content of File1.");
addFileToDirectory(&directory, file1);
return 0;
}
43
b. Two level directory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct FileEntry {
char name[50];
char content[1000];
};
struct Directory {
char name[50];
struct FileEntry files[MAX_FILES];
int num_files;
};
int num_dirs = 0;
struct Directory directories[MAX_DIRS];
44
if (strcmp(directories[i].name, parent_name) == 0) {
if (directories[i].num_files >= MAX_FILES) {
printf("Error: Maximum files reached in %s.\n", parent_name);
return;
}
strcpy(directories[num_dirs].name, dir_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
num_dirs++;
printf("Directory %s created in %s.\n", dir_name, parent_name);
return;
}
}
strcpy(directories[i].files[directories[i].num_files].name, file_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
45
printf("File %s created in %s.\n", file_name, dir_name);
return;
}
}
int main() {
strcpy(directories[0].name, "root");
directories[0].num_files = 0;
num_dirs++;
46
createDirectory("root", "docs");
createDirectory("root", "images");
createFile("docs", "document1.txt");
createFile("docs", "document2.txt");
createFile("images", "image1.jpg");
listFiles("docs");
listFiles("images");
return 0;
}
47
8. Develop a C program to simulate the Linked file allocation strategies.
#include <stdio.h>
#include <stdlib.h>
int main(){
int f[50], p, i, st, len, j, c, k, a;
for (i = 0; i < 50; i++)
f[i] = 0;
printf("Enter how many blocks already allocated: ");
scanf("%d", &p);
printf("Enter blocks already allocated: ");
for (i = 0; i < p; i++) {
scanf("%d", &a);
f[a] = 1;
}
x:
printf("Enter index starting block and length: ");
scanf("%d%d", &st, &len);
k = len;
if (f[st] == 0)
{
for (j = st; j < (st + k); j++){
if (f[j] == 0){
f[j] = 1;
printf("%d --- >", j);
}
else{
//printf("%d Block is already allocated \n", j);
k++;
}
48
}
}
else
printf("%d starting block is already allocated \n", st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if (c == 1)
goto x;
else
exit(0);
return 0;
}
49
9. Develop a C program to simulate SCAN disk scheduling algorithm.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
int pos[] = {90,120,35,122,38,128,65,68};
for(i=1;i<=n;i++)
{
//scanf("%d",&temp);
temp = pos[i-1];
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
50
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]<queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
51
//queue[i]=max;
//queue[i+1]=0;
for(i=temp1+1,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}
52