KEMBAR78
OS Lab Manual | PDF | Computer File | Filename
0% found this document useful (0 votes)
6 views44 pages

OS Lab Manual

Uploaded by

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

OS Lab Manual

Uploaded by

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

RAJIV GANDHI COLLEGE OF ENGINEERING,

RESEARCH & TECHNOLOGY


CHANDRAPUR, MAHARASHTRA

LAB MANUAL

Scheme: 2024-2025

Branch: B.TECH-CSE

Year and Semester: II YEAR/IV Semester

OPERATING SYSTEMS AMD PYTHON


PROGRAMMING LAB

Computer Science & Engineering


Dr, Babasaheb Ambedkar Technological University, (DBATU) Lonere

BTCOL406-Operating Systems & Python Programming Lab

List of Experiments:

1. Hands on Unix Commands


2. Shell programming for file handling
3. Shell script programming using the commands grep, awk, and sed
4. Implementation of CPU scheduling algorithms-i) FCFS ii) SJF iii) Priority
5. Concurrent programming; use of threads and processes, system calls (fork, v-
fork)
6. Implementation of Producer-Consumer problem
7. Implementation of Bounded Buffer Producer-Consumer problem Synchronization
primitives-Semaphores
8. Implementation of various memory allocation algorithms-First-Fit, Best-Fit and
Worst-Fit
9. Implementation of various page replacement algorithms
i) FIFO ii) Optimal iii) LRU
10. Implementation of Disk Scheduling Algorithms-FCFS, SSTF
Ex. No.: 1

Date:

HANDS ON UNIX COMMANDS

AIM: To try following 10 UNIX Commands on shell prompt

COMMANDS:

1. pwd
pwd stands for Print Work directory. it shows the current directory.

2. ls
It presents the contents of a particular directory – both files and directories.
Ex:
ls- lists files in current directory
ls –alF : list in long format

3. cd
Change Directory, the cd command is used to move from one directory to another.
Ex:
cd tempdir : change directory to tempdir
cd .. : move back one directory
cd ~dhyatt/web-docs :move into dhyatt web docs directory

4. mkdir
It lets you create folders anywhere you like in your Linux system
Ex:
mkdir graphics : make a directory called graphics

5. rmdir
the rmdir command allows you to delete specific folders from your system without any
hassles
Ex:
rmdir emptydir : Remove directory (must be empty)

6. rm
remove or delete file
rm file1.bak : removes file1.bak file
rm *.tmp : remove all .tmp files
7. mv
move or rename files
Ex:
mv old.html new.html
8. lpr
send file to printer
Ex:
Lpr.index.html : send index.html to printer
9. man
online manual (help) about command
Ex:
man ls : will give help about ls command
10. cp
The cp command is just a short way of telling your machine to copy a file or directory from one
folder to another.
11. mount
Contrary to Windows, whenever SD card or a USB is pluge-in , chances are it won‟t show them
directly at the start. It needs to mount it with existing file system using the mount command.
12. df
The df command displays essential information about the disk space on the file system. It
is used widely by system administrators to monitor and analyze real-time server or
network-oriented systems.
13. uname
The uname command is used for obtaining system information like name, version, and other
system-specific details. We can quickly check our OS and kernel version with this command.
14. kill
The kill command is a powerful way to stop processes that are stuck due to resource
constraints.
15. batch
If you are looking for a neat tool that will run system services in a pre-defined schedule,
16. shutdown
The shutdown command is here for empowering your Linux terminal commands skills to a
whole new level.
17. cat
Designed initially for concatenating multiple files, the cat command is used for numerous
other purposes since. This is among other Linux commands you will use to create new files,
view file contents in the terminal, and redirect output to another command-line tool or file.
18. head
The head command allows you to view the beginning of a file or piped data directly from
the terminal. It‟s one of the most widely used Linux commands by users who works
heavily with text processing.
Short for a move, it‟s a supplement to the cut operation you perform in the GUI. Just like cp,
you can use the mv command to move either single or multiple files from one location to
another.
19. cmp
If you want to compare two files and print the result to the standard output stream, the cmp
command will let you do exactly so
20. ln
The ln command is one of the handiest Linux commands for creating symbolic links to some
specific file.
21. alias
It is one of the most used Linux commands by system admins as it lets them replace a word
by another string in files directly from the terminal.
22. comm.
you can use comm to compare two files for common and distinct lines.
Ex. No.: 2

Date:

SHELL PROGRAMMING FOR FILE HANDLING

AIM: To try shell programming UNIX Commands for file handling

 Shell scripting offers some operators as well as some commands to check and perform
different properties and functionalities associated with the file.
 For our convenience, we create a file named „abc.txt‟ and another .sh file to execute
different functions or operations on that file. Operations may be reading the contents of
the file or testing the file type.

File Reading Functionalities:


Shell scripting offers some functionalities for reading the file, reversing the contents,
counting words, lines, etc.

 Reading line by line: First, we take input using the read command then run the while
loop which runs line after line.

Script:
#!/bin/bash
read -p "Enter file name : " filename
while read line
do
echo $line
done < $filename

 Counting characters, words & lines in the file:


We take three variables, one for counting characters, words, and lines respectively.
We use „wc‟ command, which stands for word count and counts the number of
characters and words as well. For counting lines, we pass „grep „which keeps count of
the lines that match a pattern. Then we print out each variable.

Script:
#! /bin/bash

echo Enter the filename


read file
c=`cat $file | wc -c`
w=`cat $file | wc -w`
l=`grep -c "." $file`
echo Number of characters in $file is $c
echo Number of words in $file is $w
echo Number of lines in $file is $l

 Display file contents in reverse: To print the contents of any file in reverse, we use tac or
nl, sort, cut commands. Tac is simply the reverse of a cat and simply prints the file in
reverse order. Whereas nl commands numbers, the file contents sort the numbered file
in the reverse order, and the cut command removes the number and prints the file
contents.

Script:
$ nl abc.txt | sort -nr | cut -f 2-

 File Test Operators


-b file: This operator checks if the file is a block special file or not and returns true or
false subsequently. It is [-b $file] syntactically.

Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name

if [ -b $file_name ]
then
echo "$file_name is a block special file"
else
echo "$file_name is not a block special file"
fi
 -d file: The operator looks over if the file is present as a directory. If Yes, it returns true
else false. It is [-d $file] syntactically.

Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name

if [ -d $file_name ]
then
echo "$file_name is a directory"
else
echo "$file_name is not a directory"
fi

 -e file: The operator inspects if the file exists or not. Even if a directory is passed, it
returns true if the directory exists. It is [-e $file] syntactically.

Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name

if [ -e $file_name ]
then
echo "$file_name exist"
else
echo "$file_name not exist"
fi
 -f file: If the file is an ordinary file or special file, then it returns true else false. It is [-f
$file] syntactically.

Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name

if [ -f $file_name ]
then
echo "$file_name is file"
else
echo "$file_name is not file"
fi

 -s file: This operator checks if the file has a size greater than zero or not, which returns
true or false subsequently. It is [-s $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name

if [ -s $file_name ]
then
echo "$file_name has size>0"
else
echo "$file_name has size= 0"
fi

 -x file: The operator looks over if the file is executable or not, and returns true and false
subsequently. It is [-x $file] syntactically.

Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -x $file_name ]
then
echo "$file_name is executable"
else
echo "$file_name is not executable"
fi
Ex. No.: 3

Date:

SHELL SCRIPT PROGRAMMING USING THE COMMANDS grep, awk and sed

AIM: To try shell script programming using grep, awk and sed commands

COMMANDS:

grep:
The grep filter searches a file for a particular pattern of characters, and displays all lines that
contain that pattern. The pattern that is searched in the file is referred to as the regular
expression (grep stands for global search for regular expression and print out).

Syntax:

grep [options] pattern [files]

Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

-A n : Prints searched line and nlines after the result.


-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.

$cat > geekfile.txt


unix is great os. unix is opensource. unix is free os.
learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
1. Case insensitive search : The -i option enables to search for a string case insensitively in the
given file. It matches the words like “UNIX”, “Unix”, “unix”.

$grep -i "UNix" geekfile.txt


Output:

unix is great os. unix is opensource. unix is free os.


Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
awk:

awk is a scripting language used for manipulating data and generating reports. The
awk command programming language requires no compiling and allows the user to
use variables, numeric functions, string functions, and logical operators.

Awk is a utility that enables a programmer to write tiny but effective programs in
the form of statements that define text patterns that are to be searched for in each
line of a document and the action that is to be taken when a match is found within a
line. Awk is mostly used for pattern scanning and processing. It searches one or
more files to see if they contain lines that matches with the specified patterns and
then perform the associated actions.

1. AWK Operations:
(a) Scans a file line by line
(b) Splits each input line into fields
(c) Compares input line/fields to pattern
(d) Performs action(s) on matched lines

2. Useful For:
(a) Transform data files
(b) Produce formatted reports

3. Programming Constructs:
(a) Format output lines
(b) Arithmetic and string operations
(c) Conditionals and loops

Syntax:
awk options 'selection _criteria {action }' input-file > output-file

options:
-f program-file : Reads the AWK program source from the file
program-file, instead of from the
first command line argument.
-F fs : Use fs for the input field separator

$cat > employee.txt


Default behavior of Awk: By default Awk prints every line of data from the specified file.
$ awk '{print}' employee.txt
Output:
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000

2. Print the lines which match the given pattern.


$ awk '/manager/ {print}' employee.txt
Output:
ajay manager account 45000
varun manager sales 50000
amit manager account 47000

3. Splitting a Line Into Fields : For each record i.e line, the awk command splits the record
delimited by whitespace character by default and stores it in the $n variables. If the line has 4
words, it will be stored in $1, $2, $3 and $4 respectively. Also, $0 represents the whole line.
$ awk '{print $1,$4}' employee.txt
Output:
ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000

Built-In Variables In Awk


 NR: NR command keeps a current count of the number of input records. Remember that
records are usually lines. Awk command performs the pattern/action statements once for
each record in a file.
 NF: NF command keeps a count of the number of fields within the current input record.
 FS: FS command contains the field separator character which is used to divide fields on the
input line. The default is “white space”, meaning space and tab characters. FS can be
reassigned to another character (typically in BEGIN) to change the field separator.
 RS: RS command stores the current record separator character. Since, by default, an input
line is the input record, the default record separator character is a newline.
 OFS: OFS command stores the output field separator, which separates the fields when Awk
prints them. The default is a blank space. Whenever print has several parameters separated
with commas, it will print the value of OFS in between each parameter.
 ORS: ORS command stores the output record separator, which separates the output lines
when Awk prints them. The default is a newline character. print automatically outputs the
contents of ORS at the end of whatever it is given to print.

Use of NR built-in variables (Display Line Number)


$ awk '{print NR,$0}' employee.txt
Output:
1 ajay manager account 45000
2 sunil clerk account 25000
3 varun manager sales 50000
4 amit manager account 47000
5 tarun peon sales 15000
6 deepak clerk sales 23000
7 sunil peon sales 13000
8 satvik director purchase 80000
Ex. No.: 4(a)

Date:

FIRST COME FIRST SERVE (FCFS) SCHEDULING

AIM: To write the program to implement First Come First Serve (FCFS) CPU
Scheduling algorithm

ALGORITHM:

1. Start the program


2. Get the number of processes and their burst times
3. Initialize the waiting time for process 1 to 0.
4. Process for(i=2;i<=n;i++), wt for p[i] = wt of p[i-1] + bt of p[i-1]
5. The waiting time of all the processes is summed then average value time is
calculated.
6. The waiting time of each process and average times are displayed
7. Stop the program
PROGRAM:

#include <stdio.h>
#include <conio.h>

struct process
{
int pid;
int bt;
int wt, tt;
}p[10];

int main()
{
int i,n,totwt,tottt;
float avg1,avg2;
//clrscr();
printf("Enter the no of process \n"); scanf("%d",&n);

for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("Enter the burst time \n"); scanf("%d",&p[i].bt);
}

p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt; p[i].tt=p[i].bt+p[i].wt;
i++;
}
i=1;
totwt=tottt=0;
printf("\n processid \t bt\t wt\t tt\n");
while(i<=n)
{
printf("\n\t%d \t%d \t%d \t%d",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
avg1=(float)totwt/n; avg2=(float)tottt/n; printf("\navg1=%.2f \t avg2=%.2f \t",avg1,avg2);
getch();
return 0;
}

OUTPUT:

Enter the no of process: 3


Enter the burst time: 2
Enter the burst time: 4
Enter the burst time: 6

Process id bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12

avg1= 2.67 avg2= 6.67

RESULT:

Thus the FIFO CPU scheduling program was executed and verified successfully.
Ex. No.: 4(b)

Date:

SHORTEST JOB FIRST (SJF) SCHEDULING

AIM: To write the program to implement Shortest Job First (SJF) CPU Scheduling
algorithm

ALGORITHM:

1. Start the program


2. Get the number of processes and their burst times
3. Initialize the waiting time for process 1 to 0.
4. The processes are stored according to their burst time.
5. The waiting time for the processes are calculated a follows:
6. for(i=2;i<=n;i++).
wt of p[i] = wt of p[i-1] + bt of p[i-1]
7. The waiting time of all the processes summed and then the average time is
calculated
8. The waiting time of each processes and average time are displayed.
9. Stop the program

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct process
{
int pid;
int bt;
int wt;
int tt;
}p[10],temp;

int main()
{
int i,j,n,totwt,tottt;
float avg1,avg2;
//clrscr();
printf("\nEnter the number of process:\t");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter the burst time:\t");
scanf("%d",&p[i].bt);
}

for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].bt>p[j].bt)
{
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;p[i].bt=p[j].bt;
p[j].bt=temp.bt;
}
}
}

p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;

while(i<=n){
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++;
}

i=1;
totwt=tottt=0;
printf("\nProcess id \tbt \twt \ttt");
while(i<=n){
printf("\n\t%d \t%d \t%d t%d\n",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}

avg1=(float)totwt/n;
avg2=(float)tottt/n;

printf("\nAVG1=%.2f\t AVG2=%.2f",avg1,avg2);
getch();
return 0;
}

OUTPUT:

Enter the no of process: 3


Enter the burst time: 2
Enter the burst time: 4
Enter the burst time: 6

Process id bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12

avg1= 2.67 avg2= 6.67

RESULT:

Thus the SJF CPU scheduling program was executed and verified successfully.
Ex. No.: 4(c)

Date:

PRIORITY CPU SCHEDULING

AIM: To write a C program to implement Priority CPU Scheduling algorithm

ALGORITHM:

1. Start the program


2. Get the number of processes and their burst times and Priorities
3. Initialize the waiting time for process 1 to 0.
4. Based on the priorities processes are arranged
5. The waiting time of all the processes is summed then average waiting time is
computed
6. The waiting time of each process and average waiting time are displayed based on
the priority.
7. Stop the program

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct process
{
int pid;
int bt;
int wt;
int tt;
int prior;
}
p[10],temp;
int main()
{
int i,j,n,totwt,tottt;
float arg1,arg2;
//clrscr();
printf("enter the number of process");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("enter the burst time");
scanf("%d",&p[i].bt);
printf("\n enter the priority");
scanf("%d",&p[i].prior);
}
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].prior>p[j].prior)
{
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;
p[i].bt=p[j].bt;
p[j].bt=temp.bt;
temp.prior=p[i].prior;
p[i].prior=p[j].prior;
p[j].prior=temp.prior;
}
}
}
p[i].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++;
}
i=1;
totwt=tottt=0;
printf("\n process to \t bt \t wt \t tt");
while(i<=n)
{
printf("\n%d\t %d\t %d\t %d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
arg1= (float)totwt/n;
arg2=(float)tottt/n;
printf("\n arg1=%.2f \t arg2=%.2f\t",arg1,arg2);
getch();
return 0;
}

OUTPUT:

enter the no of process:3


enter the burst time:2
enter the priority:3
enter the burst time:4
enter the priority:1
enter the burst time:6
enter the priority:2

process to bt wt tt
1 4 0 4 4
2 6 4 10 14
3 2 10 12 22

avg1=4
avg2=8

RESULT:

Thus the priority scheduling program was executed and verified successfully
Ex. No.: 5

Date:

CONCURRENT PROGRAMMING

AIM: To write a C program to implement threads and processes using system calls
(fork and v-fork)

ALGORITHM:

fork() System Call:


Fork system call is used for creating a new process, which is called child process, which
runs concurrently with the process that makes the fork() call (parent process). After a new
child process is created, both processes will execute the next instruction following the
fork() system call. A child process uses the same pc(program counter), same CPU
registers, same open files which use in the parent process.
It takes no parameters and returns an integer value. Below are different values returned by
fork().
Negative Value: creation of a child process was unsuccessful.
Zero: Returned to the newly created child process.
Positive value: Returned to parent or caller. The value contains process ID of newly created
child process.

#include <stdio.h>
#include <sys/types.h>
int main()
{
fork();
fork();
fork();
printf("hello\n");
return 0;
}

Output:
hello
hello
hello
hello
hello
hello
hello
hello
The number of times „hello‟ is printed is equal to number of process created. Total Number
of Processes = 2n, where n is number of fork system calls. So here n = 3, 2 3 = 8.

vfork() :
Vfork() is also system call which is used to create new process. New process created by
vfork() system call is called child process and process that invoked vfork() system call is
called parent process. Code of child process is same as code of its parent process. Child
process suspends execution of parent process until child process completes its execution
as both processes share the same address space.

include<stdio.h>
#include<unistd.h>
int main(void)
{
printf("Before fork\n");
vfork();
printf("after fork\n");
}
Ex. No.: 6

Date:

PROCESS SYNCRONIZATION

AIM: To write a C program to implement Bounded-Buffer Producer-Consumer


Problem

ALGORITHM:
1. Declare variable for producer & consumer as pthread-t-tid produce tid consume
2. Declare a structure to add items, semaphore variable set as struct
3. Read number the items to be produced and consumed
4. Declare and define semaphore function for creation and destroy
5. Define producer function
6. Define consumer function.
7. Call producer and consumer
8. Stop the execution.

PROGRAM:
(PRODUCER-CONSUMER PROBLEM)
#include <stdio.h>

void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0;
in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf("\n1. Produce \t 2. Consume \t3. Exit");
printf("\nEnter your choice: =");
scanf("%d", &choice);
switch(choice)
{
case 1: if((in+1)%bufsize==out)
printf("\nBuffer is Full");
else
{
printf("\nEnter the value: ");
scanf("%d", &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;
case 2: if(in == out)
printf("\nBuffer is Empty");
else
{
consume = buffer[out];
printf("\nThe consumed value is %d", consume);
out = (out+1)%bufsize;
}
break;
}
}
}

OUTPUT:
1. Produce 2. Consume 3. Exit
Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit
Enter your choice: 3

RESULT: Thus the producer consumer program was executed and verified
successfully
Ex. No.: 7

Date:

SEMAPHORES

AIM: To write a C program to implement Bounded-Buffer Producer-Consumer


Problem using Synchronization primitives-Semaphores

ALGORITHM:
1. Declare and define semaphore function for creation and destroy
2. Define producer function
3. Define consumer function.
4. Call producer and consumer
5. Stop the execution.

PROGRAM

#include <stdio.h>
#include <stdlib.h>

// Initialize a mutex to 1
int mutex = 1;

// Number of full slots as 0


int full = 0;

// Number of empty slots as size


// of buffer
int empty = 10, x = 0;

// Function to produce an item and


// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;

// Increase the number of full


// slots by 1
++full;
// Decrease the number of empty
// slots by 1
--empty;

// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);

// Increase mutex value by 1


++mutex;
}

// Function to consume an item and


// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;

// Decrease the number of full


// slots by 1
--full;

// Increase the number of empty


// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;

// Increase mutex value by 1


++mutex;
}

// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");

// Using '#pragma omp parallel for'


// can give wrong value due to
// synchronization issues.

// 'critical' specifies that code is


// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical

for (i = 1; i > 0; i++) {

printf("\nEnter your choice:");


scanf("%d", &n);

// Switch Cases
switch (n) {
case 1:

// If mutex is 1 and empty


// is non-zero, then it is
// possible to produce
if ((mutex == 1)
&& (empty != 0)) {
producer();
}

// Otherwise, print buffer


// is full
else {
printf("Buffer is full!");
}
break;

case 2:

// If mutex is 1 and full


// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}

// Otherwise, print Buffer


// is empty
else {
printf("Buffer is empty!");
}
break;

// Exit Condition
case 3:
exit(0);
break;
}
}
}
Ex. No.: 8

Date:

MEMORY ALLOCATION ALGORITHM

AIM: To write a C program to implement (a) First-Fit (b) Best-Fit and (c) Worst-Fit
Memory Allocation Algorithm

First Fit
In the first fit approach is to allocate the first free partition or hole large enough
which can accommodate the process. It finishes after finding the first suitable free
partition.
Best Fit
The best fit deals with allocating the smallest free partition which meets the
requirement of the requesting process. This algorithm first searches the entire list of
free partitions and considers the smallest hole that is adequate. It then tries to find a
hole which is close to actual process size needed.
Worst fit
In worst fit approach is to locate largest available free portion so that the portion left
will be big enough to be useful. It is the reverse of best fit.

ALGORITHM:
1. Start the program.
2. Get the segment size, number of process to be allocated and their corresponding
size.
3. Get the options. If the option is „2‟ call first fit function.
4. If the option is „1‟ call best fit function. Otherwise exit.
5. For first fit, allocate the process to first possible segment which is free and set the
personnel slap as „1‟. So that none of process to be allocated to segment which is
already allocated and vice versa.
6. For best fit, do the following steps,.
7. Sorts the segments according to their sizes.
8. Allocate the process to the segment which is equal to or slightly greater than the
process size and set the flag as the „1‟ .So that none of the process to be allocated
to the segment which is already allocated and vice versa.
9. Stop the program
PROGRAM: (FIRST FIT MEMORY MANAGEMENT)

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max], b[max], f[max],i,j,nb,nf,temp;
static int bf[max], ff[max];
clrscr();
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files:-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragment");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

OUTPUT:
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5 Block 2: 2 Block 3: 7
Enter the size of the files:-
File 1: 1 File 2: 4

OUTPUT

File No File Size Block No Block Size Fragment


1 1 3 7 6
2 4 1 5 1
Ex. No.: 9

Date:

PAGE REPLACEMENT ALGORITHM

AIM: To write a C program to implement 1) FIFO 2) Optimal and 3) LRU page


replacement algorithm

ALGORITHM:
1. Start to traverse the pages.
2. If the memory holds fewer pages, then the capacity else goes to step 5.
3. Push pages in the queue one at a time until the queue reaches its maximum
capacity or all page requests are fulfilled.
4. If the current page is present in the memory, do nothing.
5. Else, pop the topmost page from the queue as it was inserted first.
6. Replace the topmost page with the current page from the string.
7. Increment the page faults.
8. Stop

PROGRAM

program for FIFO page replacement algorithm


#include <stdio.h>
int main()
{
int incomingStream[] = {4, 1, 2, 4, 5};
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;
}
Output –

Incoming Frame 1 Frame 2 Frame 3


4 4 - -
1 4 1 -
2 4 1 2
4 4 1 2
5 5 1 2

Total Page Faults: 4

Optimal Page Replacement Algorithm


#include<stdio.h>
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j,
k, pos, max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

printf("Enter page reference string: ");

for(i = 0; i < no_of_pages; ++i){


scanf("%d", &pages[i]);
}

for(i = 0; i < no_of_frames; ++i){


frames[i] = -1;
}

for(i = 0; i < no_of_pages; ++i){


flag1 = flag2 = 0;

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


if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

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


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}

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


if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}
if(flag3 ==0){
max = temp[0];
pos = 0;

for(j = 1; j < no_of_frames; ++j){


if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}
printf("\n");

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


printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);

return 0;
}

Output
Enter number of frames: 3
Enter number of pages: 10
Enter page reference string: 2 3 4 2 1 3 7 5 4 3
2 -1 -1
2 3 -1
234
234
134
134
734
534
534
534
LRU Page Replacement Algorithm
#include<stdio.h>

int findLRU(int time[], int n){


int i, minimum = time[0], pos = 0;

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


if(time[i] < minimum){
minimum = time[i];
pos = i;
}
}
return pos;
}

int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j,
pos, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);
printf("Enter number of pages: ");
scanf("%d", &no_of_pages);
printf("Enter reference string: ");
for(i = 0; i < no_of_pages; ++i){
scanf("%d", &pages[i]);
}

for(i = 0; i < no_of_frames; ++i){


frames[i] = -1;
}

for(i = 0; i < no_of_pages; ++i){


flag1 = flag2 = 0;

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


if(frames[j] == pages[i]){
counter++;
time[j] = counter;
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
counter++;
faults++;
frames[j] = pages[i];
time[j] = counter;
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
pos = findLRU(time, no_of_frames);
counter++;
faults++;
frames[pos] = pages[i];
time[pos] = counter;
}

printf("\n");

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


printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);

return 0;
}

Output
Enter number of frames: 3
Enter number of pages: 6
Enter reference string: 5 7 5 6 7 3
5 -1 -1
5 7 -1
5 7 -1
576
576
376
Total Page Faults = 4
Ex. No.: 10

Date:

DISK SCHEDULING ALGORITHM

AIM: To write a C program to implement 1) FCFS 2) SSTF Disk Scheduling algorithm

PROGRAM (FCFS)

#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);

// logic for FCFS disk scheduling

for(i=0;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}

printf("Total head moment is %d",TotalHeadMoment);


return 0;

}
Output:-

Enter the number of Request


8
Enter the Requests Sequence
95 180 34 119 11 123 62 64
Enter initial head position
50
Total head movement is 644

PROGRAM : (SSTF)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial,count=0;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);

// logic for sstf disk scheduling

/* loop will execute until all process is completed*/


while(count!=n)
{
int min=1000,d,index;
for(i=0;i<n;i++)
{
d=abs(RQ[i]-initial);
if(min>d)
{
min=d;
index=i;
}

}
TotalHeadMoment=TotalHeadMoment+min;
initial=RQ[index];
// 1000 is for max
// you can use any number
RQ[index]=1000;
count++;
}

printf("Total head movement is %d",TotalHeadMoment);


return 0;
}

OUTPUT:

Enter the number of Request


8
Enter Request Sequence
95 180 34 119 11 123 62 64
Enter initial head Position
50
Total head movement is 236

You might also like