KEMBAR78
OS-Lab Manual | PDF | Computer Engineering | Software Engineering
0% found this document useful (0 votes)
17 views44 pages

OS-Lab Manual

The document provides C programs for various operating system concepts including process management, CPU scheduling algorithms, producer-consumer problem using semaphores, interprocess communication with FIFO, and Banker's algorithm for deadlock avoidance. It includes implementations for single and multiple processes, scheduling algorithms like FCFS, SJF, Round Robin, and Priority scheduling. Additionally, it covers semaphore-based synchronization in producer-consumer scenarios and demonstrates interprocess communication using named pipes.

Uploaded by

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

OS-Lab Manual

The document provides C programs for various operating system concepts including process management, CPU scheduling algorithms, producer-consumer problem using semaphores, interprocess communication with FIFO, and Banker's algorithm for deadlock avoidance. It includes implementations for single and multiple processes, scheduling algorithms like FCFS, SJF, Round Robin, and Priority scheduling. Additionally, it covers semaphore-based synchronization in producer-consumer scenarios and demonstrates interprocess communication using named pipes.

Uploaded by

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

Operating Systems Laboratory

1. Develop a c program to implement the Process system calls (fork (), exec(),
wait(), create process,terminate process)
a. Single process
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t child_pid;
int status;
// Create a child process
child_pid = fork();
if (child_pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (child_pid == 0) {
// Child process
printf("Child process (PID: %d) is running.\n",
getpid()); // Replace the child process with a new
program execlp("/bin/ls", "ls", "-l", NULL);
// If exec fails, the code below will be executed
perror("Exec failed");
exit(1);

} else {
/ Parent process
printf("Parent process (PID: %d) created a child (PID: %d).\n", getpid(), child_pid);
/ Wait for the child process to
finish wait(&status);
if (WIFEXITED(status)) {
printf("Child process (PID: %d) exited with status %d.\n",
child_pid, WEXITSTATUS(status));
} else {
printf("Child process (PID: %d) did not exit normally.\n", child_pid);
}
}
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)
{
sleep(1);
exit(100 + i);
}
}
/ Using waitpid() and printing exit status
/ of children.
for (i=0; i<5; i++)
{
pid_t cpid = waitpid(pid[i], &stat, 0);
if (WIFEXITED(stat))
printf("Child %d terminated with status: %d\n",
cpid, WEXITSTATUS(stat));
}
}
Driver code int main()
{
waitexample();

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.
a. FCFS
#include<stdio.h>
#include<string.h>
int main()
{
char pn[10][10],t[10];
int arr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,j,n,temp;
int totwt=0,tottat=0;
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter the ProcessName, Arrival Time& Burst Time:");
scanf("%s%d%d",&pn[i],&arr[i],&bur[i]);
}
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(arr[i]<arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
temp=bur[i];
bur[i]=bur[j];
bur[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}

}
}
for(i=0; i<n; i++)
{
if(i==0)
star[i]=arr[i];
else
star[i]=finish[i-1];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
printf("\nPName Arrtime Burtime WaitTime Start TAT Finish");
for(i=0; i<n; i++)
{
printf("\n%s\t%3d\t%3d\t%3d\t%3d\t%6d\t
%6d",pn[i],arr[i],bur[i],wt[i],star[i],tat[i],finish[i]);
totwt+=wt[i];
tottat+=tat[i];
}
printf("\nAverage Waiting time:%f",(float)totwt/n);
printf("\nAverage Turn Around Time:%f",(float)tottat/n);
return 0;
}

b. SJF

#include<stdio.h>
#include<string.h>
int main()
{
int et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10];
int totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
//clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter process name, arrival time& execution time:");
//flushall();
scanf("%s%d%d",pn[i],&at[i],&et[i]);
}
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(et[i]<et[j])
{
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0; i<n; i++)
{
if(i==0)
st[i]=at[i];
else
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime");
for(i=0; i<n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
return 0;
}

c. Round Robin
#include<stdio.h>
main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
clrscr();
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t) {
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else {
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++){
wa[i]=tat[i]-
ct[i]; att+=tat[i];
awt+=wa[i];}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
getch();}
d. Priority Scheduling
#include<stdio.h>
#include<string.h>
int main()
{
int et[20],at[10],n,i,j,temp,p[10],st[10],ft[10],wt[10],ta[10];
int totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
//clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter process name,arrivaltime,execution time & priority:");
//flushall();
scanf("%s%d%d%d",pn[i],&at[i],&et[i],&p[i]);
}
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(p[i]<p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0; i<n; i++)

if(i==0)
{
st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime");
for(i=0; i<n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],p[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
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>
#define BUFFER_SIZE 20
sem_t empty, full;
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int size=50;
void* producer(void* arg) {
int item = 1;
while (1) {
sem_wait(&empty);
buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
item++;
sem_post(&full);
if(item>size){
break;
}}
printf("Sending completed\n ");
pthread_exit(NULL);
}
void* consumer(void* arg) {
int item;
while (1) {
sem_wait(&full);
item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
sem_post(&empty);
if(item==size){
printf("Received all");
break;
}
}

pthread_exit(NULL);
}
int main() {
pthread_t producer_thread, consumer_thread;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_create(&producer_thread, NULL, producer, NULL);

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

pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
4. Develop a C program which demonstrates interprocess communication
between a reader process and a writer process. Use mkfifo, open, read, write and
close APIs in your program. A Write First
// C program to implement one side of
FIFO // This side writes first, then reads
#include <stdio.h>
#include <string.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <unistd.h>

int main()
{
int fd;

// FIFO file path


char * myfifo = "/tmp/myfifo";

/ Creating the named file(FIFO)


/ mkfifo(<pathname>,

<permission>) mkfifo(myfifo, 0666);

char arr1[80], arr2[80];


while (1)
{
// Open FIFO for write only
fd = open(myfifo, O_WRONLY);
/ Take an input arr2ing from user.
/ 80 is maximum length

fgets(arr2, 80, stdin);

/ Write the input arr2ing on FIFO


/ and close it
write(fd, arr2, strlen(arr2)+1);
close(fd);

// Open FIFO for Read only


fd = open(myfifo, O_RDONLY);

/ Read from FIFO

read(fd, arr1,

sizeof(arr1));

/ Print the read


message printf("User2:
%s\n", arr1); close(fd);
}
return 0;
}
b. Read First
/ C program to implement one side of FIFO
/ This side reads first, then reads
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{

int fd1;

// FIFO file path


char * myfifo = "/tmp/myfifo";

// Creating the named file(FIFO)


// mkfifo(<pathname>,<permission>)
mkfifo(myfifo, 0666);

char str1[80], str2[80];


while (1)
{
// First open in read only and read
fd1 = open(myfifo,O_RDONLY);
read(fd1, str1, 80);

// Print the read string and close


printf("User1: %s\n", str1);
close(fd1);

/ Now open in write mode and write


/ string taken from user.
fd1 = open(myfifo,O_WRONLY);
fgets(str2, 80, stdin);
write(fd1, str2, strlen(str2)+1);
close(fd1);
}
return 0;
}
5. Develop a C program to simulate Bankers Algorithm for DeadLock
Avoidance.. a. Single process allottment
#include <stdio.h>

#include <stdbool.h>

// Define the number of processes and resources


#define NUM_PROCESSES 5
#define NUM_RESOURCES 3

// Maximum resources needed by each process


int max[NUM_PROCESSES][NUM_RESOURCES] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}

};

// Currently allocated resources for each process


int allocation[NUM_PROCESSES][NUM_RESOURCES] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};

// Available resources
int available[NUM_RESOURCES] = {3, 3, 2};
// Need resources for each process
int need[NUM_PROCESSES][NUM_RESOURCES];

/ Function to calculate the need


matrix void calculateNeedMatrix() {
for (int i = 0; i < NUM_PROCESSES; i++)
{ for (int j = 0; j < NUM_RESOURCES; j++)
{

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


}
}
}

/ Function to check if a process can be granted resources

bool canGrantResources(int process, int request[]) {

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


if (request[i] > need[process][i] || request[i] >
available[i]) { return false;
}
}
return true;
}

/ Function to simulate resource allocation


void allocateResources(int process, int request[]) {

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


allocation[process][i] += request[i];
available[i] -= request[i];
need[process][i] -= request[i];

}
}

int main() {
calculateNeedMatrix();

int requestProcess = 1;
int request[NUM_RESOURCES] = {1, 2, 2};

if (canGrantResources(requestProcess, request))
{ allocateResources(requestProcess, request);
printf("Resources granted to process %d.\n",
requestProcess); printf("Updated allocation matrix:\n");
for (int i = 0; i < NUM_PROCESSES; i++) {
for (int j = 0; j < NUM_RESOURCES; j++) {
printf("%d ", allocation[i][j]);
}
printf("\n");
}
} else {
printf("Resources cannot be granted to process %d.\n", requestProcess);

return 0;
}
b. Multiple process allottment
/ Banker's Algorithm

#include <stdio.h>

int main()
{
/ P0, P1, P2, P3, P4 are the Process
names here int n, m, i, j, k;
n = 5; // Number of processes m =

3; // Number of resources

int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix


{2,0,0},//P1
{3,0,2},//P2
{2,1,1},//P3
{0,0,2}};//P4
int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{3,2,2},//P1
{9,0,2},//P2
{2,2,2},//P3
{4,3,3}};//P4
int avail[3] = { 3, 3, 2 }; // Available Resources
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
}
}
if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);
// This code is contributed by Deep Baldha (CandyZack)
}
6. Develop a C program to simulate the following contiguous memory allocation

Techniques: a) Worst fit b) Best fit c) First fit.

a. Worst fit
#include <stdio.h>

// Define the maximum number of memory

blocks #define MAX_BLOCKS 100

// Structure to represent memory blocks


struct MemoryBlock {
int block_id;
int size;
int allocated;

};

// Function to perform worst-fit memory allocation


void worstFit(struct MemoryBlock blocks[], int m, int processSize) {
int worstIdx = -1;

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


if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (worstIdx == -1 || blocks[i].size > blocks[worstIdx].size) {
worstIdx = i;
}
}
}

if (worstIdx != -1) {
/ Allocate the memory block

blocks[worstIdx].allocated = 1;

printf("Process with size %d allocated to block %d\n", processSize,


worstIdx + 1); } else {
printf("Cannot allocate the process with size %d\n", processSize);
}

int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);

struct MemoryBlock blocks[MAX_BLOCKS];

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


blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}

int n; // Number of processes


printf("Enter the number of processes: ");
scanf("%d", &n);

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


int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
worstFit(blocks, m, processSize);

return 0;
}

b. Best fit
#include <stdio.h>

// Define the maximum number of memory blocks


#define MAX_BLOCKS 100

// Structure to represent memory blocks


struct MemoryBlock {
int block_id;
int size;
int allocated;
};

// Function to perform best-fit memory allocation


void bestFit(struct MemoryBlock blocks[], int m, int processSize) {
int bestIdx = -1;

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


if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (bestIdx == -1 || blocks[i].size < blocks[bestIdx].size) {
bestIdx = i;
}
}
}

if (bestIdx != -1) {
/ Allocate the memory block

blocks[bestIdx].allocated = 1;

printf("Process with size %d allocated to block %d\n", processSize,


bestIdx + 1); } else {
printf("Cannot allocate the process with size %d\n", processSize);
}

int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);

struct MemoryBlock blocks[MAX_BLOCKS];

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


blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}

int n; // Number of processes


printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
bestFit(blocks, m, processSize);
}

return 0;
}

b1. Best fit


#include <stdio.h>

/ Number of memory blocks

#define NUM_BLOCKS 5

/ Number of processes

#define NUM_PROCESSES 5

/ Sizes of memory blocks


int memory_blocks[NUM_BLOCKS] = {100, 500, 200, 300, 600};

// Sizes of processes
int process_sizes[NUM_PROCESSES] = {212, 417, 112, 426, 112};

/ Array to keep track of whether a block is allocated

or not int allocated[NUM_BLOCKS] = {0};


/ Function to perform Best Fit memory
allocation void bestFit() {
for (int i = 0; i < NUM_PROCESSES; i+
+) { int best_fit_index = -1;
for (int j = 0; j < NUM_BLOCKS; j++) {
if (!allocated[j] && memory_blocks[j] >= process_sizes[i]) {
if (best_fit_index == -1 || memory_blocks[j] <
memory_blocks[best_fit_index]) { best_fit_index = j;
}
}
}

if (best_fit_index != -1) {
allocated[best_fit_index] = 1;
printf("Process %d (size %d) is allocated to Block %d (size %d)\n",
i, process_sizes[i], best_fit_index,
memory_blocks[best_fit_index]); } else {
printf("Process %d (size %d) cannot be allocated\n", i, process_sizes[i]);
}
}
}

int main() {

bestFit();

return 0;
}
c. First fit
#include <stdio.h>

// Define the maximum number of memory

blocks #define MAX_BLOCKS 100

// Structure to represent memory blocks


struct MemoryBlock {
int block_id;
int size;
int allocated;

};

// Function to perform first-fit memory allocation


void firstFit(struct MemoryBlock blocks[], int m, int processSize) {
for (int i = 0; i < m; i++) {
if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
// Allocate the memory block
blocks[i].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, i + 1);
return;
}
}
printf("Cannot allocate the process with size %d\n", processSize);
}

int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);

struct MemoryBlock blocks[MAX_BLOCKS];

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


blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}

int n; // Number of processes


printf("Enter the number of processes: ");
scanf("%d", &n);

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


int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
firstFit(blocks, m, processSize);
}

return 0;
}
7. Develop a C program to simulate page replacement algorithms:
a) FIFO b) LRU

a. FIFO
#include <stdio.h>
int main()
{
int incomingStream[] = {4 , 1 , 2 , 4 , 5,4,1,2,3,6};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;
pages = sizeof(incomingStream)/sizeof(incomingStream[0]);

printf(" Incoming \t Frame 1 \t Frame 2 \t Frame 3 "); int

temp[ frames ];

for(m = 0; m < frames; m++)


{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}

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

#include<stdio.h>

#include<limits.h>

int checkHit(int incomingPage, int queue[], int occupied){

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


if(incomingPage == queue[i])
return 1;
}

return 0;
}

void printFrame(int queue[], int occupied)


{
for(int i = 0; i < occupied; i++)
printf("%d\t\t\t",queue[i]);
}

int main()
{

/ int incomingStream[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1};


/ int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2,

4, 3}; int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3};

int n = sizeof(incomingStream)/sizeof(incomingStream[0]);

int frames = 3;
int queue[n];
int distance[n];
int occupied = 0;
int pagefault = 0;

printf("Page\t Frame1 \t Frame2 \t Frame3\n");

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


{
printf("%d: \t\t",incomingStream[i]);
// what if currently in frame 7
// next item that appears also 7
// didnt write condition for HIT

if(checkHit(incomingStream[i], queue, occupied)){


printFrame(queue, occupied);
}

// filling when frame(s) is/are empty


else if(occupied < frames){
queue[occupied] = incomingStream[i];
pagefault++;
occupied++;

printFrame(queue, occupied);
}
else{

int max = INT_MIN;

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;
}
if(distance[j] > max){
max = distance[j];
index = j;
}
}
queue[index] = incomingStream[i];
printFrame(queue, occupied);
pagefault++;

}
printf(“\n”);

printf("Page Fault: %d",pagefault);

return 0;
}
8. Simulate following File Organization Techniques: a) Single level

directory b) Two level directory

a. Single level directrry


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/ Maximum number of files in the

directory #define MAX_FILES 100

/ Maximum file name length


#define MAX_NAME_LENGTH 256

/ File structure to represent


files typedef struct File {
char name[MAX_NAME_LENGTH];
int size;

char content[1024]; // For simplicity, we use a fixed

content size } File;

/ Directory structure to hold files


typedef struct Directory {
File files[MAX_FILES];
int num_files;
} Directory;
// Function to create a new file
File createFile(const char* name, int size, const char* content) {
File newFile;
strncpy(newFile.name, name,
MAX_NAME_LENGTH); newFile.size = size;
strncpy(newFile.content, content,
sizeof(newFile.content)); return newFile;
}

// Function to add a file to the directory


void addFileToDirectory(Directory* directory, File
file) { if (directory->num_files < MAX_FILES) {
directory->files[directory->num_files] = file;
directory->num_files++;
} else {
printf("Directory is full. Cannot add more files.\n");
}
}

// Function to display the contents of the directory


void displayDirectoryContents(const Directory*
directory) { printf("Directory Contents:\n");
for (int i = 0; i < directory->num_files; i++) {
printf("File: %s, Size: %d\n", directory->files[i].name, directory->files[i].size);
}
}

int main() {
Directory directory;
directory.num_files = 0;
// Create and add files to the directory
File file1 = createFile("File1.txt", 100, "This is the content of

File1."); addFileToDirectory(&directory, file1);

File file2 = createFile("File2.txt", 200, "Content of File2 goes

here."); addFileToDirectory(&directory, file2);


/ Display the directory contents

displayDirectoryContents(&directory);

return 0;
}
b. Two level directory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_DIRS 100


#define MAX_FILES 100

struct FileEntry {
char name[50];
char content[1000];

};

struct Directory {
char name[50];
struct FileEntry files[MAX_FILES];
int num_files;
};

int num_dirs = 0;
struct Directory directories[MAX_DIRS];

void createDirectory(char parent_name[], char dir_name[]) {


if (num_dirs >= MAX_DIRS) {
printf("Error: Maximum directories reached.\n");
return;
}

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


if (strcmp(directories[i].name, parent_name) == 0)

{ if (directories[i].num_files >= MAX_FILES) {

printf("Error: Maximum files reached in %s.\n",


parent_name); return;

strcpy(directories[num_dirs].name, dir_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
num_dirs++;
printf("Directory %s created in %s.\n", dir_name, parent_name);
return;
}
}

printf("Error: Parent directory not found.\n");


}

void createFile(char dir_name[], char file_name[]) {


for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, dir_name) == 0) {
if (directories[i].num_files >= MAX_FILES) {
printf("Error: Maximum files reached in %s.\n", dir_name);
return;
}

strcpy(directories[i].files[directories[i].num_files].name, file_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
printf("File %s created in %s.\n", file_name,
dir_name); return;
}
}

printf("Error: Directory not found.\n");


}

void listFiles(char dir_name[]) {


for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, dir_name) == 0) {
printf("Files in directory %s:\n", dir_name);
for (int j = 0; j < directories[i].num_files; j++) {
printf("%s\n", directories[i].files[j].name);
}
return;
}
}

printf("Error: Directory not found.\n");


}

int main() {
strcpy(directories[0].name, "root");
directories[0].num_files = 0;
num_dirs++;

char parent[50], dir[50], file[50];


createDirectory("root", "docs");
createDirectory("root", "images");
createFile("docs", "document1.txt");
createFile("docs", "document2.txt");
createFile("images", "image1.jpg");
listFiles("docs");
listFiles("images");

return 0;
}
9. Develop a C program to simulate the Linked file allocation
strategies. #include <stdio.h>
#include <stdlib.h>

int main(){

int f[50], p, i, st, len, j, c, k,


a; for (i = 0; i < 50; i++)
f[i] = 0;
printf("Enter how many blocks already
allocated: "); scanf("%d", &p);
printf("Enter blocks already allocated:
"); for (i = 0; i < p; i++) {
scanf("%d",
&a); f[a] = 1;
}
x:
printf("Enter index starting block and
length: "); scanf("%d%d", &st, &len);
k = len;
if (f[st] == 0)
{
for (j = st; j < (st + k); j++)
{ if (f[j] == 0){
f[j] = 1;
printf("%d---->", j);
}
else{
//printf("%d Block is already allocated \n",
j); k++;
}
}
}
else
printf("%d starting block is already allocated \n", st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if (c == 1)
goto x;
else
exit(0);
return 0;
}
10. Develop a C program to simulate SCAN disk scheduling
algorithm. #include<stdio.h>
#include<stdlib.h>

int main()

{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],

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++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]<queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
//queue[i]=max;
//queue[i+1]=0;
for(i=temp1+1,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}

You might also like