0% found this document useful (0 votes)
1 views47 pages

OS Lab Manual

The document contains multiple programming experiments related to operating systems, including CPU scheduling algorithms, file allocation strategies, memory allocation techniques, and disk scheduling algorithms. Each experiment includes code snippets in C++ to demonstrate the implementation of various algorithms such as FCFS, worst-fit, first-fit, and the Banker's algorithm. The document also provides sample outputs for each program, showcasing their functionality.

Uploaded by

backupno2zara
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)
1 views47 pages

OS Lab Manual

The document contains multiple programming experiments related to operating systems, including CPU scheduling algorithms, file allocation strategies, memory allocation techniques, and disk scheduling algorithms. Each experiment includes code snippets in C++ to demonstrate the implementation of various algorithms such as FCFS, worst-fit, first-fit, and the Banker's algorithm. The document also provides sample outputs for each program, showcasing their functionality.

Uploaded by

backupno2zara
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/ 47

Operating System

EXP NO: 1 Program for FCFS CPU Scheduling Algorithms to find turnaround time and
Date: waiting time.

#include<iostream>

using namespace std;

// Function to find the waiting time for all

// processes

void findWaitingTime(int processes[], int n,

int bt[], int wt[])

// waiting time for first process is 0

wt[0] = 0;

// calculating waiting time

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

wt[i] = bt[i-1] + wt[i-1] ;

// Function to calculate turn around time

void findTurnAroundTime( int processes[], int n,

int bt[], int wt[], int tat[])

1
Operating System

// calculating turnaround time by adding

// bt[i] + wt[i]

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

tat[i] = bt[i] + wt[i];

//Function to calculate average time

void findavgTime( int processes[], int n, int bt[])

int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes

findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes

findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details

cout << "Processes "<< " Burst time "

<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn

// around time
2
Operating System

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

total_wt = total_wt + wt[i];

total_tat = total_tat + tat[i];

cout << " " << i+1 << "\t\t" << bt[i] <<"\t "

<< wt[i] <<"\t\t " << tat[i] <<endl;

cout << "Average waiting time = "

<< (float)total_wt / (float)n;

cout << "\nAverage turn around time = "

<< (float)total_tat / (float)n;

// Driver code

int main()

//process id's

int processes[] = { 1, 2, 3};

int n = sizeof processes / sizeof processes[0];

//Burst time of all processes

int burst_time[] = {10, 5, 8};


3
Operating System

findavgTime(processes, n, burst_time);

return 0;

Output:

Processes Burst time Waiting time Turn around time //The Output is Wrong please correct it

1 10 0 10

2 5 10 15

3 8 15 23

Average waiting time = 8.33333

Average turn around time = 16

EXP NO: 2 Program for File Allocation Strategies - Sequential Memory


Date:

#include <iostream>

#include <conio.h>

using namespace std;

void recurse(int files[]){

4
Operating System

int flag = 0, startBlock, len, k;

cout << "Enter the starting block and the length of the files: ";

cin >> startBlock >> len;

for (int j=startBlock; j<(startBlock+len); j++){

if (files[j] == 0)

flag++;

if(len == flag){

for (int k=startBlock; k<(startBlock+len); k++){

if (files[k] == 0){

files[k] = 1;

cout << k <<"\t" << files[k] << endl;

if (k != (startBlock+len-1))

cout << "The file is allocated to the disk" << endl;

else

cout << "The file is not allocated to the disk" << endl;

5
Operating System

cout << "Do you want to enter more files?" << endl;

int ch;

cout << "Press 1 for YES, 0 for NO: ";

cin >> ch;

if (ch == 1)

recurse(files);

else

exit(0);

return;

int main()

int files[50];

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

files[i]=0;

cout << "Files Allocated are :" << endl;

recurse(files);

getch();

return 0;

6
Operating System

EXP NO: 3
Program for File Allocation Strategies - Indexed Memory
Date:

#include <iostream>

#include <conio.h>

#include <stdlib.h>

using namespace std;

int files[50], indexBlock[50], indBlock, n;

void recurse1();

void recurse2();

void recurse1(){

cout << "Enter the index block: ";

cin >> indBlock;

if (files[indBlock] != 1){

cout << "Enter the number of blocks and the number of files needed for the index " << indBlock << " on the disk:
";

cin >> n;

}
7
Operating System

else{

cout << indBlock << " is already allocated" << endl;

recurse1();

recurse2();

void recurse2(){

int flag = 0;

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

cin >> indexBlock[i];

if (files[indexBlock[i]] == 0)

flag++;

if (flag == n){

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

files[indexBlock[j]] = 1;

cout << "Allocated" << endl;

8
Operating System

cout << "File Indexed" << endl;

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

cout << indBlock << " ------> " << indexBlock[k] << ": " << files[indexBlock[k]] << endl;

else{

cout << "File in the index is already allocated" << endl;

cout << "Enter another indexed file" << endl;

recurse2();

cout << "Do you want to enter more files?" << endl;

cout << "Enter 1 for Yes, Enter 0 for No: ";

int ch;

cin >> ch;

if (ch == 1)

recurse1();

else

exit(0);

return;

9
Operating System

int main()

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

files[i]=0;

recurse1();

return 0;

10
Operating System

EXP NO: 4
Program to simulate the following contiguous memory allocation techniques
Date: Worst-fit

#include<bits/stdc++.h>

using namespace std;

// Function to allocate memory to blocks as per worst fit

// algorithm

void worstFit(int blockSize[], int m, int processSize[],

int n)

// Stores block id of the block allocated to a

// process

int allocation[n];

// Initially no block is assigned to any process

memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks

11
Operating System

// according to its size ad assign to it

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

// Find the best fit block for current process

int wstIdx = -1;

for (int j=0; j<m; j++)

if (blockSize[j] >= processSize[i])

if (wstIdx == -1)

wstIdx = j;

else if (blockSize[wstIdx] < blockSize[j])

wstIdx = j;

// If we could find a block for current process

if (wstIdx != -1)

12
Operating System

// allocate block j to p[i] process

allocation[i] = wstIdx;

// Reduce available memory in this block.

blockSize[wstIdx] -= processSize[i];

cout << "\nProcess No.\tProcess Size\tBlock no.\n";

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

cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";

if (allocation[i] != -1)

cout << allocation[i] + 1;

else

cout << "Not Allocated";

cout << endl;

13
Operating System

// Driver code

int main() {

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

int processSize[] = {212, 417, 112, 426};

int m = sizeof(blockSize)/sizeof(blockSize[0]);

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

worstFit(blockSize, m, processSize, n);

return 0 ; }

Output
Process No. Process Size Block no.
1 212 5
2 417 2
3 112 5
4 426 Not Allocated

EXP NO: 5
Program to simulate the following contiguous memory allocation techniques First-
Date: fit

#include<bits/stdc++.h>

14
Operating System

using namespace std;

// Function to allocate memory to

// blocks as per First fit algorithm

void firstFit(int blockSize[], int m,

int processSize[], int n)

// Stores block id of the

// block allocated to a process

int allocation[n];

// Initially no block is assigned to any process

memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks

// according to its size ad assign to it

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

15
Operating System

for (int j = 0; j < m; j++)

if (blockSize[j] >= processSize[i])

// allocate block j to p[i] process

allocation[i] = j;

// Reduce available memory in this block.

blockSize[j] -= processSize[i];

break;

cout << "\nProcess No.\tProcess Size\tBlock no.\n";

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

16
Operating System

cout << " " << i+1 << "\t\t"

<< processSize[i] << "\t\t";

if (allocation[i] != -1)

cout << allocation[i] + 1;

else

cout << "Not Allocated";

cout << endl;

// Driver code

int main()

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

int processSize[] = {212, 417, 112, 426};

int m = sizeof(blockSize) / sizeof(blockSize[0]);

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

17
Operating System

firstFit(blockSize, m, processSize, n);

return 0 ;

Output :

Process No. Process Size Block no.


1 212 2
2 417 5
3 112 2
4 426 Not Allocated

EXP NO: 6
Program for bankers algorithm
Date:

#include<iostream>
using namespace std;

// Number of processes
const int P = 5;

// Number of resources
const int R = 3;

// Function to find the need of each process


void calculateNeed(int need[P][R], int maxm[P][R],
int allot[P][R])
18
Operating System

{
// Calculating Need of each P
for (int i = 0 ; i < P ; i++)
for (int j = 0 ; j < R ; j++)

// Need of instance = maxm instance -


// allocated instance
need[i][j] = maxm[i][j] - allot[i][j];
}

// Function to find the system is in safe state or not

bool isSafe(int processes[], int avail[], int maxm[][R],

int allot[][R])

int need[P][R];

// Function to calculate need matrix

calculateNeed(need, maxm, allot);

// Mark all processes as infinish

bool finish[P] = {0};

// To store safe sequence

int safeSeq[P];

19
Operating System

// Make a copy of available resources

int work[R];

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

work[i] = avail[i];

// While all processes are not finished

// or system is not in safe state.

int count = 0;

while (count < P)

// Find a process which is not finish and

// whose needs can be satisfied with current

// work[] resources.

bool found = false;

for (int p = 0; p < P; p++)

// First check if a process is finished,

20
Operating System

// if no, go for next condition

if (finish[p] == 0)

// Check if for all resources of

// current P need is less

// than work

int j;

for (j = 0; j < R; j++)

if (need[p][j] > work[j])

break;

// If all needs of p were satisfied.

if (j == R)

// Add the allocated resources of

// current P to the available/work

// resources i.e.free the resources

for (int k = 0 ; k < R ; k++)

21
Operating System

work[k] += allot[p][k];

// Add this process to safe sequence.

safeSeq[count++] = p;

// Mark this p as finished

finish[p] = 1;

found = true;

// If we could not find a next process in safe

// sequence.

if (found == false)

cout << "System is not in safe state";

22
Operating System

return false;

// If system is in safe state then

// safe sequence will be as below

cout << "System is in safe state.\nSafe"

" sequence is: ";

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

cout << safeSeq[i] << " ";

return true;

// Driver code

int main()

int processes[] = {0, 1, 2, 3, 4};

23
Operating System

// Available instances of resources

int avail[] = {3, 3, 2};

// Maximum R that can be allocated

// to processes

int maxm[][R] = {{7, 5, 3},

{3, 2, 2},

{9, 0, 2},

{2, 2, 2},

{4, 3, 3}};

// Resources allocated to processes

int allot[][R] = {{0, 1, 0},

{2, 0, 0},

{3, 0, 2},

{2, 1, 1},

{0, 0, 2}};

24
Operating System

// Check system is in safe state or not

isSafe(processes, avail, maxm, allot);

return 0;

Output:
System is in safe state.
Safe sequence is: 1 3 4 0 2

25
Operating System

EXP NO: 7
Program to simulate disk scheduling algorithms SCAN
Date:

#include<bits/stdc++.h>
using namespace std;
int main(){
int i,j,k,n,m,sum=0,x,y,h;
cout<<"Enter the size of disk\n";
cin>>m;
cout<<"Enter number of requests\n";
cin>>n;
cout<<"Enter the requests\n";
vector <int> a(n),b;
for(i=0;i<n;i++){
cin>>a[i];
}
for(i=0;i<n;i++){
if(a[i]>m){
cout<<"Error, Unknown position "<<a[i]<<"\n";
return 0;
}
}
cout<<"Enter the head position\n";
cin>>h;
int temp=h;
a.push_back(h);
a.push_back(m);
a.push_back(0);
sort(a.begin(),a.end());
for(i=0;i<a.size();i++){
if(h==a[i])
break;
}
k=i;
26
Operating System

if(k<n/2){
for(i=k;i<a.size();i++){
b.push_back(a[i]);
}
for(i=k-1;i>=0;i--){
b.push_back(a[i]);
}
}
else{
for(i=k;i>=0;i--){
b.push_back(a[i]);
}
for(i=k+1;i<a.size();i++){
b.push_back(a[i]);
}
}
temp=b[0];
cout<<temp;
for(i=1;i<b.size();i++){
cout<<" -> "<<b[i];
sum+=abs(b[i]-temp);
temp=b[i];
}
cout<<'\n';
cout<<"Total head movements = "<< sum<<'\n';
cout<<"Average head movement = "<<(float)sum/n<<'\n';
return 0;
}
OUTPUT:

Enter the size of disk


199
Enter number of requests
8
Enter the requests
98 183 37 122 14 124 65 67
Enter the head position
53
53 -> 65 -> 67 -> 98 -> 122 -> 124 -> 183 -> 199 -> 37 -> 14 -> 0
Total head movements = 345
Average head movement = 43.125

27
Operating System

EXP NO: 8
Program for Page Replacement Algorithms LRU
Date:

#include<bits/stdc++.h>

using namespace std;

// Function to find page faults using indexes

28
Operating System

int pageFaults(int pages[], int n, int capacity)

// To represent set of current pages. We use

// an unordered_set so that we quickly check

// if a page is present in set or not

unordered_set<int> s;

// To store least recently used indexes

// of pages.

unordered_map<int, int> indexes;

// Start from initial page

int page_faults = 0;

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

// Check if the set can hold more pages

if (s.size() < capacity)

29
Operating System

// Insert it into set if not present

// already which represents page fault

if (s.find(pages[i])==s.end())

s.insert(pages[i]);

// increment page fault

page_faults++;

// Store the recently used index of

// each page

indexes[pages[i]] = i;

// If the set is full then need to perform lru

// i.e. remove the least recently used page

// and insert the current page

else

30
Operating System

// Check if current page is not already

// present in the set

if (s.find(pages[i]) == s.end())

// Find the least recently used pages

// that is present in the set

int lru = INT_MAX, val;

for (auto it=s.begin(); it!=s.end(); it++)

if (indexes[*it] < lru)

lru = indexes[*it];

val = *it;

// Remove the indexes page

31
Operating System

s.erase(val);

// insert the current page

s.insert(pages[i]);

// Increment page faults

page_faults++;

// Update the current page index

indexes[pages[i]] = i;

return page_faults;

// Driver code

32
Operating System

int main()

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

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

int capacity = 4;

cout << pageFaults(pages, n, capacity);

return 0;

Output:
6

EXP NO: 9
Program to simulate producer-consumer problem using semaphores
Date:

#include<bits/stdc++.h>

33
Operating System

#include<pthread.h>

#include<semaphore.h>

#include <unistd.h>

using namespace std;

// Declaration

int r1,total_produced=0,total_consume=0;

// Semaphore declaration

sem_t notEmpty;

// Producer Section

void* produce(void *arg){

while(1){

cout<<"Producer produces item."<<endl;

cout<<"Total produced = "<<++total_produced<<

" Total consume = "<<total_consume*-1<<endl;

sem_post(¬Empty);

34
Operating System

sleep(rand()%100*0.01);

// Consumer Section

void* consume(void *arg){

while(1){

sem_wait(¬Empty);

cout<<"Consumer consumes item."<<endl;

cout<<"Total produced = "<<total_produced<<

" Total consume = "<<(--total_consume)*-1<<endl;

sleep(rand()%100*0.01);

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

// thread declaration

35
Operating System

pthread_t producer,consumer;

// Declaration of attribute......

pthread_attr_t attr;

// semaphore initialization

sem_init(¬Empty,0,0);

// pthread_attr_t initialization

pthread_attr_init(&attr);

pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);

// Creation of process

r1=pthread_create(&producer,&attr,produce,NULL);

if(r1){

cout<<"Error in creating thread"<<endl;

exit(-1);

36
Operating System

r1=pthread_create(&consumer,&attr,consume,NULL);

if(r1){

cout<<"Error in creating thread"<<endl;

exit(-1);

// destroying the pthread_attr

pthread_attr_destroy(&attr);

// Joining the thread

r1=pthread_join(producer,NULL);

if(r1){

cout<<"Error in joining thread"<<endl;

exit(-1);

r1=pthread_join(consumer,NULL);

37
Operating System

if(r1){

cout<<"Error in joining thread"<<endl;

exit(-1);

// Exiting thread

pthread_exit(NULL);

return 0;

EXP NO: 10
Program to simulate the concept of Dining-Philosophers problem.
Date:

38
Operating System

#include <bits/stdc++.h>

#include <pthread.h>

#include <unistd.h>

using namespace std;

#define N 10

#define THINKING 2

#define HUNGRY 1

#define EATING 0

#define LEFT (phnum + 4) % N

#define RIGHT (phnum + 1) % N

// Philosopher index

int phil[N];

int times = 200;

class monitor {

39
Operating System

// state of the philosopher

int state[N];

// Philosopher condition variable

pthread_cond_t phcond[N];

// mutex variable for synchronization

pthread_mutex_t condLock;

public:

// Test for the desired condition

// i.e. Left and Right philosopher are not reading

void test(int phnum)

if (state[(phnum + 1) % 5] != EATING

and state[(phnum + 4) % 5] != EATING

and state[phnum] == HUNGRY) {

40
Operating System

state[phnum] = EATING;

pthread_cond_signal(&phcond[phnum]);

// Take Fork function

void take_fork(int phnum)

pthread_mutex_lock(&condLock);

// Indicates it is hungry

state[phnum] = HUNGRY;

// test for condition

test(phnum);

41
Operating System

// If unable to eat.. wait for the signal

if (state[phnum] != EATING) {

pthread_cond_wait(&phcond[phnum], &condLock);

cout << "Philosopher " << phnum << " is Eating"

<< endl;

pthread_mutex_unlock(&condLock);

// Put Fork function

void put_fork(int phnum)

pthread_mutex_lock(&condLock);

// Indicates that I am thinking

state[phnum] = THINKING;

42
Operating System

test(RIGHT);

test(LEFT);

pthread_mutex_unlock(&condLock);

// constructor

monitor()

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

state[i] = THINKING;

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

pthread_cond_init(&phcond[i], NULL);

43
Operating System

pthread_mutex_init(&condLock, NULL);

// destructor

~monitor()

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

pthread_cond_destroy(&phcond[i]);

pthread_mutex_destroy(&condLock);

// Global Object of the monitor

phil_object;

44
Operating System

void* philosopher(void* arg)

int c = 0;

while (c < times) {

int i = *(int*)arg;

sleep(1);

phil_object.take_fork(i);

sleep(0.5);

phil_object.put_fork(i);

c++;

int main()

// Declaration...

45
Operating System

pthread_t thread_id[N];

pthread_attr_t attr;

// Initialization...

pthread_attr_init(&attr);

pthread_attr_setdetachstate(&attr,

PTHREAD_CREATE_JOINABLE);

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

phil[i] = i;

// Creating...

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

pthread_create(&thread_id[i], &attr, philosopher,

&phil[i]);

cout << "Philosopher " << i + 1 << " is thinking..."

<< endl;

46
Operating System

// Joining....

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

pthread_join(thread_id[i], NULL);

// Destroying

pthread_attr_destroy(&attr);

pthread_exit(NULL);

return 0;

47

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy