0% found this document useful (0 votes)
0 views60 pages

Os Lab Manual

The OS Lab Manual for Computer Science Engineering at JNTUK provides a comprehensive guide for students on various Unix/Linux commands and programming exercises. It includes a detailed index of experiments ranging from basic command usage to advanced scheduling algorithms and deadlock avoidance techniques. The manual serves as a practical resource for understanding operating systems through hands-on programming and simulations.
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)
0 views60 pages

Os Lab Manual

The OS Lab Manual for Computer Science Engineering at JNTUK provides a comprehensive guide for students on various Unix/Linux commands and programming exercises. It includes a detailed index of experiments ranging from basic command usage to advanced scheduling algorithms and deadlock avoidance techniques. The manual serves as a practical resource for understanding operating systems through hands-on programming and simulations.
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/ 60

lOMoARcPSD|54868014

OS LAB Manual

COMPUTER SCIENCE ENGINEERING (Jawaharlal Nehru Technological University,


Kakinada)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Rajkumar V ([email protected])
lOMoARcPSD|54868014

LAB MANUAL

OPERATING SYSTEMS

II B.TECH I SEM
(JNTUK)

(R20)
COMPUTER SCIENCE AND ENGINEERING

V S M COLLEGE OF ENGINEERING

RAMCHANDRAPURAM

E.G. Dt. - 533255

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

INDEX

SL. NO EXP NAME OF THE EXPERIMENT PAGE NO.


NO.
1 1) Study of Unix/Linux general purpose utility command list:
1 man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more,
1-6
date, time, kill, history, chmod, chown, finger, pwd, cal, logout,
shutdown
2 Write a C program that makes a copy of a file using standard I/O,
2 and system calls. 7-8

Write a C program to emulate the UNIX ls –l command


3 3 9-10
write a LINUX/UNIX C Program for the Implementation of
4 Producer Consumer Algorithm using Semaphore. 11-12
4
5 write C program to illustrate concurrent execution of threads
5 using pthreads library. 13-15

6 6 write C program to illustrate concurrent execution of threads


16-17
using pthreads library.
7 7 Write a c program to implement ROUND ROBIN 18-20
SCHEDULING
8 8 Write a c program to implement SJF SCHEDULING 21-23
ALGORITHMS
9 9 Write a c program to implement FCFS SCHEDULING 24-25
10 10 Write a c program to implement PRIORITY SCHEDULING 26-28
11 11 Simulate the Multiprogramming with a fixed number of tasks
29-30
(MFT)
12 12 Simulate the Multiprogramming with a variable number of tasks
31-32
(MVT)
13 13 Simulate Bankers Algorithm for Dead Lock Avoidance. 33-36
14 14 Simulate Bankers Algorithm for Dead Lock Prevention. 37-41
15 15 Simulate the page replacement algorithm FIFO 42-43
16 16 Simulate the page replacement algorithm LRU 44-46
17 17 Simulate the page replacement algorithm LFU. 47-50
18 18 Simulate the Sequenced File allocation strategies. 51-52
19 19 Simulate the Indexed File allocation strategies. 53-54
20 20 Simulate the Linked File allocation strategies. 55-56

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment-1

AIM: Study of Unix/Linux general purpose utility command list man,who,cat, cd, cp, ps, ls,
mv, rm, mkdir, rmdir, echo, more, date, time, kill, history, chmod, chown, finger, pwd, cal,
logout, shutdown.
Description:
Introduction
The purpose of this document is to provide the reader with a fast and simple
introduction to using the Linux command shell and some of its basic utilities. It is assumed
that the reader has zero or very limited exposure to the Linux command prompt. This
document is designed to accompany an instructor-led tutorial on this subject, and therefore
some details have been left out. Explanations, practical examples, and references to DOS
commands are made, where appropriate.
What is a command shell?
 A program that interprets commands
 Allows a user to execute commands by typing them manually at a terminal, or
automatically in programs called shell scripts.
 A shell is not an operating system. It is a way to interface with the operating system and
run commands.
What is BASH?
 BASH = Bourne Again SHell
 Bash is a shell written as a free replacement to the standard Bourne Shell (/bin/sh)
originally written by Steve Bourne for UNIX systems.
 It has all of the features of the original Bourne Shell, plus additions that make it easier
to program with and use from the command line.
 Since it is Free Software, it has been adopted as the default shell on most Linux
systems.
Executing Commands
The Command PATH:
 Most common commands are located in your shell's “PATH”, meaning that you can
just type the name of the program to execute it.
Example: Typing “ ls” will execute the “ ls” command.
 Your shell's “PATH” variable includes the most common program locations, such as
/bin, /usr/bin, /usr/X11R6/bin, and others.
 To execute commands that are not in your current PATH, you have to give the
complete location of the command.
Examples: /home/bob/myprogram
./program (Execute a program in the current directory)
~/bin/program (Execute program from a personal bin directory)

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Command Syntax
 Commands can be run by themselves, or you can pass in additional arguments to make
them do different things. Typical command syntax can look something like this:
Command [-argument] [-argument] [--argument] [file]
Examples:
o ls List files in current directory
o ls -l Lists files in “long” format
o ls -l –color As above, with colorized output
o cat filename Show contents of a file
o cat -n filename Show contents of a file, with line numbers
List Commands with Examples:
1. man #show complete detail of a command
Syntax: man command_name
It is basically short form of manual and will tell you detail about other
commands you pass to it as argument. It will explain you what that particular command
do, how it work, what options it will take and so on. Basically, if you remember name
of any command, you can get all detail of it with man command.
Example:
$ man man # it will tell about how to use man itself
$ man sudo # will tell you all about sudo command
$ man dpkg # will tell you all about dpkg command

2. Cat # will be used to create a file, read a file, concenate content of many files.
syntax : cat [options] [input_filename] [> or >>] [output_filename]
# All the things in [] is optional i,e cat can work without them also
NOTE:
1. If you do not provide output_filename the output will be printed on terminal
itself i,e terminal is the standard output for cat command.
2. > and >> both are called append operator i,e write content to a file but > will
erase the file of content if exist and write to it but >> will add the new
content to the existing content , so it is safer to use >> instead of>
Example:
venki@venki-linux:~$ cat -n test_file1 #the -n option will print the line no also
1 I have pressed enter on last line to reach here
2 again pressed enter to come to next line and keep writing
3 All content I am writing will get written to test_files1

VSM COLLEGE OF ENGINEERING Page 1

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

3. cd #changing directory
Syntax: cd directory_name # you can pass directory_name or .. or ~ to cd

Examples:
$ cd myfolder # take you inside myfolder
$ cd .. # take you out from current folder to the previous folder
$ cd ~ # take you out of every previous folder to the root of terminal.

4. ps # It means process status and return all the running process with name and PID
Syntax: ps [options] # you can see all the available options with ps – -help
Examples:
$ ps # will return currently active process
$ ps -e # will return all the running process
$ ps –ef # will return all running process with full detail
$ ps -ef | less # as process list is very long, we have piped the output of ps -
ef to less command. It help you to display result in small
blocks and let you to scroll down to see more.
5. ls # Listing files and folders
Syntax: ls [options] #options are optional, if you do not pass it will take the
default, you can see complete list of options with ls -help
Examples:
$ ls #will list all folder and files but not hidden files or folder
$ ls –a # will list hidden files and folders also
$ ls –B #will not list the backup file ending with ~
$ ls -l # will do complete listing with all details like owner, date,
permission etc. but will not show hidden file
$ ls -l -a –B #will do all the above.
6. Mv # It will move file or directory to other location. if the location of source
destination is same the file or directory will be get renamed.
Syntax: mv [options] source destination # If two files are provided as source and
destination source will be renamed as destination. If you pass more then
two argument and the last one is directory all the previous will be treated
as source and will be moved into the last directory, but if the last
argument is not directory it will throw error.

Examples:

VSM COLLEGE OF ENGINEERING Page 2

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

$ mv myfile.txt myfile.rb # it will rename myfile.txt to myfile.rb i,e the


name is changed.
$ mv -bvi myfile.txt myfile.rb # here we are passing some option b will backup
the file before renaming, i will ask your yes no before renaming and v will print
what going on the console
$ mv test1 test_folder myfile.rb /home/venki/my_folder # it will move the file
test , myfile.rb and the test_folder to /home/venki/my_folder.
7. rm # removing file or folder, by default it remove only files to remove a folder, you
need to pass additional options
Syntax: rm [options] file_or_directory_name #options are optional, if you do not pass it
will take the default, you can see list of options with rm – -help
Example:
$ rm my_file # will remove my_file
$ rm -f my_file # will not throw error if my_file do not exist i,e it will
ignore the removal
$ rm -fi my_file # Will ignore if file is not there and ask you to press Y
to delete the file i,e it will become interactive
$ rm -r my_folder # The -r option must be passed to delete a folder other
while it will not delete it
$ rm -rf my_folder # will delete the folder and will not complain if the
folder do not exist.
8. mkdir # creating directory
Syntax: mkdir [options] directory_name #options are optional, if you do not pass it will
take the default, you can see list of options with mkdir – -help
Example:
$ mkdir myfolder
$ mkdir -p myfolder1/myfolder2/myfolder3 # -p option tell to create
nested directory with parent child relation. Thus myfolder3 will be created
in myfolder2 and so on
$ mkdir -p myfolder # the p option means parent , if the directory already
exist do not throw error but use the existing directory as parent
$ mkdir -pv -m 777 myfolder # it will not complain if directory exist, set
the permission to 777 and also print the task it performing on terminal
9. rmdir #it will list empty directory

VSM COLLEGE OF ENGINEERING Page 3

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Syntax: rmdir [options] directory_name # without argument it will delete all empty
directory name passed to it. It will throw error if directory is not empty. for that case
use rm as above
Examples:
$ rmdir dir1 dir2 dir3 # it will delete the empty directory dir1 dir2 dir3
$ rmdir -p dir1/dir2/dir3/dir4 # It will delete the parent also if deleting the
child make it empty, so first dir4 will be deleted then dir3 then dir2 and so on.
10. echo # you can use it to write a string to file or terminal itself
Syntax: echo string [filename] # file name is optional if you do not pass it the output
will be printed to the terminal unlike cat, it can use to write single string to a file or
terminal i.e. you can write multiple lines as with cat command
Example:
$ echo I am venki # it will print the output to terminal
I am venki
$ echo I am Venki to test_file >> test_file # it will append the string
to the test_file, if test_file is not present >> operator will create it and the append
to it
$ cat test_file # we will see the content of test_file
I am venki to test_file
$ echo I am adding one more line >> test_file # one more line is appended
$ cat test_file # you can see both the line
I am venki to test_file
I am adding one more line
11. More # it can be also used to display content of a file on terminal.
syntax: more [options] file_name # By default It do not provide scroll down facility
like less to see the whole content but show only that much content which fit into your
screen. However, using different options you can set the no of line you want to see,
which will activate the scrolling if the set line not come on the screen
Examples:
$ more myfile # will show that much content of file which fit in screen
$ more -100 + 50 myfile # will show 100 lines of file starting from line 50
$ more +/”I am venki” -100 # will show 100 line of the file from the line
which contain “I am venki”
$ more -s -u -100 +50 myfile #s will cause to remove blank line from display
and u will remove underlines
12. kill # will kill the process whose PID is passed to it

VSM COLLEGE OF ENGINEERING Page 4

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Syntax: kill [signals] PID # there is 60 type of signal which can be passed to kill, but
you have to just remember 9which is called SIGKILL, the default signal passed
is 15 which is called SIGTERM. Actually, kill do not kill the process itself instead, it
just pass proper signal to a process which cause it to terminate i.e. logic of termination
is in every process itself.
NOTE: the complete list of signal available for kill can be listed with kill -l
Examples:
$ kill 485 #will terminate the process with PID 485. Here the default
sigma 15 get passed, there may be chance that it fail to kill the process, say if it is
making some system call
$ kill -9 485 # it will be guaranteed that the process will be called. If the
process is making any system call, it will wait and kill it when it return from the
call.
13. history # will show you all the command you have typed in past
Syntax: history #it do not take any argument
Example:
$ history # will list all command used in past
$ history | grep netbeans # since we have piped the result of history to
grep it will return only those command , which contain word history in them.
14. Chmode #Change the permission of file to octal, which can be found
separately for user,group,world by adding,
i. 4-read(r)
ii. 2-write(w)
iii. 1-execute(x)
Syntax: chmod [OPTION] [MODE] [FILE]
Example: chmod 764 calculate.sh
Note: The number 764 is derived from:
 rwe = 4 (read) + 2 (write) + 1 (execute) = 7
 rw = 4 (read) + 2 (write) = 6
 r = 4 (read) = 4
15. chown - change file owner and group # chown changes the user and/or group
ownership of each given file. If only an owner (a user name or numeric user ID) is
given, that user is made the owner of each given file, and the files' group is not
changed.
Syntax: chown [OPTION]... OWNER [:[GROUP]] FILE

VSM COLLEGE OF ENGINEERING Page 5

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Example:
$chown remo myfile.txt
$chown root /u #Change the owner of /u to "root".
$chown root:staff /u #Likewise, but also change its group to "staff".
$chown -hR root /u #Change the owner of /u and subfiles to "root".
16. Finger - user information lookup program # Finger displays the user’s login
name, real name, terminal name and write status. (as a ‘‘*’’ after the terminal name if
write permission is denied), idle time, login time, office location and office phone
number.
Syntax: finger [-lmsp] [user ...] [user@host ...]
Example:
$ Finger
Login Name Tty Idle Login Time Office Office Phone
venki Venki *:0 Sep 12 19:16 (:0)
venki Venki pts/2 Sep 12 19:19 (:0)
$ Finger -p venki
Login: venki Name: Venki
Directory: /home/venki Shell: /bin/bash
On since Mon Sep 12 19:16 (IST) on: 0 from: 0 (Messages off)
On since Mon Sep 12 19:19 (IST) on pts/2 from: 0
No mail.
17. Pwd # will print the current working directory
Syntax: pwd [-options]
Example:
$pwd #present directory
/home/venki

18. Cal #will print the current calendar


Syntax: cal [-options]
Example: $cal
September 2016

S M Tu W Th F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

VSM COLLEGE OF ENGINEERING Page 6

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment- 2
AIM: Write a C program that makes a copy of a file using standard I/O, and system
calls.
Description:
Copying file performs an exact duplicate with a different name (or with same name but a
different drive or directory).there are no library functions; you have to write your own .the
steps are:
1. Open the source file for reading in binary mode, using binary mode ensures that the
function can copy all sorts of content not just texts.
2. Open the destination file for writing in binary mode
3. Read a character from a source file .when a file is first opened the pointer is at the start
of the file, so there is no need to position the file pointer explicitly
4. If the function FEOF () indicates that you’re reached the end of the source file, you’re
done and can close both files and return to the file pointer explicitly.
5. If you haven’t reached end-of-file, write the character to the destination file, and then
loop back.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *f1,*f2;
f1=fopen("hai.txt","w");
printf("\nEnter text & press ctrl+z at the end\n");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
printf("\nThe contents of file are\n");
f1=fopen("hai.txt","r");
while((c=getc(f1))!=EOF)
putchar(c);
fclose(f1);
printf("\nThe contents of second file that are copy from first file are\n");
f2=fopen("hai.txt","r");
while((c=getc(f2))!=EOF)
putchar(c);
fclose(f2);

VSM COLLEGE OF ENGINEERING Page 7

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

VSM COLLEGE OF ENGINEERING Page 8

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment-3

AIM: Write a C program to emulate the UNIX ls –l command

Syntax:
#include<dirent.h>
DIR *opendir(const char *pathname);
Returns:pointer if OK, NULL on error.
Pathname is the name of the directory we want to open.
struct dirent *readdir(DIR *dp);
Returns: pointer if OK, NULL at end of directory or error.
int closedir(DIR *dp);
Returns O if OK, -1 on error.

Program:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <limits.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv )
{
DIR *dir;
struct dirent *dirent;
char *where = NULL;
if (argc == 1)
where = get_current_dir_name();
else
where = argv[1];
if (NULL == (dir = opendir(where))) {
fprintf(stderr,"%d (%s) opendir %s failed\n", errno, strerror(errno), where);
return 2;
}
while (NULL != (dirent = readdir(dir))) {
printf("%s\n", dirent->d_name);
}
closedir(dir);
return 0;
VSM COLLEGE OF ENGINEERING Page 9

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

VSM COLLEGE OF ENGINEERING Page 10

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment-4

AIM: To write a C program that illustrates how to execute two commands concurrently
with a command pipe.
Description:
Pipes:-Pipes area the oldest form of Unix IPC and are provided by all UNIX systems.
They have two limitations.
1. They are half-duplex. Data flows only in one direction.
2. They can be used only between processes that have common ancestor.
Normally a pipe is created by a process, that process calls fork, and the pipe is
used between the parent and child.
The standard I/O library provides the popen and pclose functions.
The popen function creates a pipe and initiates another process that either reads from
pipe or writes to the pipe.
Syntax:-
#include<stdio.h>
FILE *popen( const char *command, const char *type);
Returns file pointer if OK, NULL on error
Here command is a shell command line. It is processed by the sh program.
int pclose(FILE * stream);
Returns termination status of shell or -1 on error.
Here pclose function closes the standard I/O stream that was created by popen, waits for the
command to terminate, and returns the termination status of the shell.
Program:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *pipein_fp, *pipeout_fp;
char readbuf[80];
/* Create one way pipe line with call to popen() */
if (( pipein_fp = popen("ls", "r")) == NULL)
{
perror("popen");
exit(1);
}

VSM COLLEGE OF ENGINEERING Page 11

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

/* Create one way pipe line with call to popen() */


if (( pipeout_fp = popen("sort", "w")) == NULL)
{
perror("popen");
exit(1);
}
/* Processing loop */
while(fgets(readbuf, 80, pipein_fp))
fputs(readbuf, pipeout_fp);
/* Close the pipes */
pclose(pipein_fp);
pclose(pipeout_fp);
return(0);
}

VSM COLLEGE OF ENGINEERING Page 12

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment-5

AIM: To write a LINUX/UNIX C Program for the Implementation of Producer


Consumer Algorithm using Semaphore.

Description:
The producer–consumer problem (also known as the bounded-buffer problem) is a
classic example of a multi-process synchronization problem. The problem describes two
processes, the producer and the consumer, who share a common, fixed-size buffer used as a
queue. The producer's job is to generate data, put it into the buffer, and start again. At the
same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at
a time. The problem is to make sure that the producer won't try to add data into the buffer if
it's full and that the consumer won't try to remove data from an empty buffer.
The solution for the producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it notifies the producer, who
starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the
buffer to be empty. The next time the producer puts data into the buffer, it wakes up the
sleeping consumer. The solution can be reached by means of inter-process communication,
typically using semaphores. An inadequate solution could result in a deadlock where both
processes are waiting to be awakened. The problem can also be generalized to have multiple
producers and consumers.

Program:
#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf(“\n 1.Producer \n 2.Consumer \n 3.Exit”);
while(1)
{
printf(“\n Enter your choice:”);

VSM COLLEGE OF ENGINEERING Page 13

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

scanf(“%d”,&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
else
printf(“Buffer is full”);
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf(“Buffer is empty”);
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s) { return (--s); }
int signal(int s) { return(++s); }
void producer() {
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf(“\n Producer produces the item %d”,x);
mutex=signal(mutex);
}
void consumer() {
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf(“\n Consumer consumes item %d”,x);
VSM COLLEGE OF ENGINEERING Page 14

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

x--;
mutex=signal(mutex);
}

VSM COLLEGE OF ENGINEERING Page 15

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment-6

AIM: To write C program to illustrate concurrent execution of threads using pthreads


library.

Description:
The POSIX thread libraries are a standards based thread API for C/C++. It allows one
to spawn a new concurrent process flow. It is most effective on multi-processor or multi-core
systems where the process flow can be scheduled to run on another processor thus gaining
speed through parallel or distributed processing. Threads require less overhead than "forking"
or spawning a new process because the system does not initialize a new system virtual
memory space and environment for the process.
While most effective on a multiprocessor system, gains are also found on uniprocessor
systems which exploit latency in I/O and other system functions which may halt process
execution. (One thread may execute while another is waiting for I/O or some other system
latency.) Parallel programming technologies such as MPI and PVM are used in a distributed
computing environment while threads are limited to a single computer system. All threads
within a process share the same address space. A thread is spawned by defining a function and
its arguments which will be processed in the thread. The purpose of using the POSIX thread
library in your software is to execute software faster.

Program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
if(iret1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);

VSM COLLEGE OF ENGINEERING Page 16

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

}
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
if(iret2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
exit(EXIT_FAILURE);
}

printf("pthread_create() for thread 1 returns: %d\n",iret1);


printf("pthread_create() for thread 2 returns: %d\n",iret2);

/* Wait till threads are complete before main continues. Unless we */


/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */

pthread_join( thread1, NULL);


pthread_join( thread2, NULL);

exit(EXIT_SUCCESS);
}

void *print_message_function( void *ptr )


{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}

VSM COLLEGE OF ENGINEERING Page 17

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment -7
AIM: Write a c program to implement ROUND ROBIN SCHEDULING

RR Description:
 Time sharing system used the round robin algorithm. Use of small time quantum allows
round robin to provide good response time. RR scheduling algorithm is a preemptive
algorithm CPU selects the process from the ready queue. To implement RR scheduling,
ready queue is maintained as a FIFO queue if the process. New processes are added to the
tail of the ready queue.
 The CPU scheduling picks the first process from the ready queue, sets a timer to interrupt
after 1 time quantum and dispatches he process. With the RR algorithm, the principal
design issue is the length of the time quantum or slice to be used.
 If the time quantum is very short, then short processes will move through the system
relatively quickly. It increases the processing overhead involved in handling the clock
interrupt and performing the scheduling and dispatching function. Thus, very short time
quantum should be avoided.

Algorithm:

Step 1: Start
2: Decloare exeCount,i,rounds:=1,finish=0,totalwaiting=0
3: Repeat steps 4 to 10 While(not isAllFinished(p,n))
4: Print “After Round #”,rounds++
5: Repeat steps 6 to 10 For I:=0 to n step 1
6: Repeat steps 7 to 9 For exeCount:=1 to exeCount<=q AND p[i].remainingTime!=0
7: Set p[i].remainingTime--
8: Set finish:=finish+1
9: if(p[i].remainingTime=0) Then → Set p[i].finishTime:=finish
[End For – exeCount]
10: Print “Remaining time ',p[i].remainingTime
[End For – I]
[End While]
11: Repeat steps 12,13 For I:=0 to n step 1
12: Print p[i].finishTime, p[i].finishTime-p[i].burstTime //this is waiting time
subtraction
13: Set totalwaiting+=p[i].finishTime-p[i].burstTime //adding total waiting
[End For]
14: Print totalwaiting, totalwaiting/n //n for no.of processes

VSM COLLEGE OF ENGINEERING Page 18

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

15: Stop
Program:

#include<stdio.h>
int main()
{
int count,j,n,time,remain,flag=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]);
wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count];
flag=0;
VSM COLLEGE OF ENGINEERING Page 19

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
return 0;
}

VSM COLLEGE OF ENGINEERING Page 20

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment -8

AIM: Write a c program to implement SJF SCHEDULING ALGORITHMS


Description:
 This algorithm associates with each process the length of the latter’s next CPU burst.
When the CPU is Free, it is assigned to the process of the ready Queue which has smallest
next CPU burst. If two process have the same length, FCFS scheduling is used to break the
file.
 SJF Scheduling algorithm is used frequently in long term scheduling. SJF algorithm may
be either preemptive or non-preemptive.
 A preemptive SJF algorithm will preempt the currently executing process, where as a non-
preemptive SJF algorithm will allow the currently running process to finish its CPU burst.
 SJF algorithm is optimal algorithm. It gives the minimum average waiting time for a given
set of processes. SJF algorithm cannot be implemented at the level of short term CPU
Scheduling. There is no way to know the length of the next CPU burst.
Algorithm:
Step 1: Start
2: Declare wt:=0,tt:=0,i //wt-for waiting time, tt-turnaround time, i -index repeating
3: Repeat step 4 For I:=0 to n step 1
4: Print p[i].pid //printing each process id in Gantt chart
[End for]
5: Repeat Steps 6 to 10 For i=0 to n step 1
6: print wt //priting waiting time
7: Set p[i].watitingtime:=wt
8: Repeat Steps 9,10 while p[i].RemainingTime>0
//each process remainingtime is initially burst time
9: Set p[i].RemainingTime:=p[i].RemaminingTime-1
10: Set Wt:=Wt+1 //increase waiting time by 1
[End While]
[End For]
11: print Wt //last process waiting time
12: Set p[i].waitingTime:=Wt
13: Repeat steps 14 to 16 For I:=0 to n step 1
14: set p[i].turnAroundTime:=(p[i].waitingTime+p[i].burstTime)-p[i].ArrivalTime
//Each process turnaround time
15: Set tt:=tt+p[i].TurnaroundTime //calculating total turnaround time 16: Set
wt:=wt+p[i].waitingTime //calculating total waiting time [End For]
17: Print “Avg turnaround time : “,tt/n
VSM COLLEGE OF ENGINEERING Page 21

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

18: Print “Avg waiting time : “,wt/n


19: Stop.

Program:

#include<stdio.h>
void main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}
//sorting burst time in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0; //waiting time for first process will be zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;

VSM COLLEGE OF ENGINEERING Page 22

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}
avg_wt=(float)total/n; //average waiting time
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

VSM COLLEGE OF ENGINEERING Page 23

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment -9

AIM: Write a c program to implement FCFS SCHEDULING


Description:
First Come First Served (FCFS) is a Non-Preemptive scheduling algorithm. FIFO (First
In First Out) strategy assigns priority to process in the order in which they request the
processor. The process that requests the CPU first is allocated the CPU first. This is easily
implemented with a FIFO queue for managing the tasks. As the process come in, they are
put at the end of the queue. As the CPU finishes each task, it removes it from the start of the
queue and heads on to the next task.
 FCFS is the simplest scheduling method CPU is allocated to the process in the order of
arrival. The process that requests the CPU first is allocated the CPU first.
 FCFS is also called FIFO.FCFS is non-preemptive scheduling algorithm implementation
of the FCFS policy is easily managed with a FIFO Queue
 When process enters the ready Queue, its process control at the head of the Queue. The
running process is removed from the queue.
 FCFS is not suitable for real time systems.
Performance matric is average waiting time. Average waiting for the FCFS is often quite
long.
Algorithm
Step 1: Start
2: Declare wt:=0, I //Waiting Time and i for index
3: Repeat step 4 for I:=0 to n step 1
4: Print p[i].pid //printing each process in Gantt chart
[End for]
5: Repeat steps 6 to 10 For I:=0 to n step 1
6: Print wt // process each waiting time
7: Set p[i].waitingTime:=wt-p[i].arrivalTime //update each process waiting time
8: Repeat Step 9,10 while p[i].burstTime>0 loop
9: p[i].bursttime-- //process each bursttime until reaches to 0
10: Set wt:=wt+1
[End While]
[End For]
11: Print wt //last proccess waiting time
12: Set p[i].waitingTime:=wt
13: Repeat step 14 for I:=0 to n step 1
14: Set wt:=wt+p[i].waitingTime //sum of all waiting times

VSM COLLEGE OF ENGINEERING Page 24

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

[End for]
15: print “Average waiting time: “,wt/n
16: Stop.
Program:
#include<stdio.h>
int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);
printf("\nEnter Process Burst Time\n");
for(i=0;i<n;i++)
{
printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
}
wt[0]=0; //waiting time for first process is 0
//calculating waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}
printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");
//calculating turnaround time
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
}
avwt/=i;
avtat/=i;
printf("\n\nAverage Waiting Time:%d",avwt);
printf("\nAverage Turnaround Time:%d",avtat);
return 0;
}

VSM COLLEGE OF ENGINEERING Page 25

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment -10

AIM: Write a c program to implement PRIORITY SCHEDULING


Description:
 CPU is allocated to the highest priority of the process form the ready Queue. Each process
has a priority number. If two or more processes have the same priority, then FCFS
algorithm is applied for soling the tie. In our examples, low numbers have the high
priority.
 Priority scheduling is preemptive or non-preemptive priority of the process can be defined
either internally or externally. Internally defined priority considers the time limits, number
of open files, use of memory and use of I/O devices. External priorities are set by using
external parameter of the process, like importance of a process, cast of process etc.
 A preemptive priority scheduling algorithm will preempt the CPU if the priority of the
newly arrived process is higher than the priority of the currently running processes. In this,
current executing process will change the state from running to ready.
 In non-preemptive scheduling algorithm, currently executing process will not change state.

Algorithm for PriorityScheduling(Process *p,integer n)


Step 1: Start
2: Declare wt:=0, I //Waiting Time and i for index
3: Repeat step 4 for I:=0 to n step 1
4: Print p[i].pid //printing each process in Gantt chart
[End for]
5: Repeat steps 6 to 10 For I:=0 to n step 1
6: Print wt // process each waiting time
7: Set p[i].waitingTime:=wt-p[i].arrivalTime //update each process waiting time
8: Repeat Step 9,10 while p[i].burstTime>0 loop
9: p[i].bursttime-- //process each bursttime until reaches to 0
10: Set wt:=wt+1
[End While]
[End For]
11: Print wt //last proccess waiting time
12: Set p[i].waitingTime:=wt
13:Repeat step 14 for I:=0 to n step 1
14: Set wt:=wt+p[i].waitingTime //sum of all waiting times
[End for]
15: print “Average waiting time : “,wt/n
16: Stop.

VSM COLLEGE OF ENGINEERING Page 26

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Program:
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);
printf("\nEnter Burst Time and Priority\n");
for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1; //contains process number
}
//sorting burst time, priority and process number in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}
temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0; //waiting time for first process is zero
//calculate waiting time
for(i=1;i<n;i++)
{

VSM COLLEGE OF ENGINEERING Page 27

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}
avg_wt=total/n; //average waiting time
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%d",avg_wt);
printf("\nAverage Turnaround Time=%d\n",avg_tat);
return 0;
}

VSM COLLEGE OF ENGINEERING Page 28

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

PAGE REPLACEMENT ALGORITHMS


Experiment -11
AIM: Simulate the Multiprogramming with a fixed number of tasks (MFT)

Description:
 If we accept that multiprogramming is a good idea, we next need to decide how to
organise the available memory in order to make effective use of the resource.
 One method is to divide the memory into fixed sized partitions. These partitions can be
of different sizes but once a partition has taken on a certain size then it remains at that
size.
 There is no provision for changing its size.

Algorithm:
Step 1: Start
2: Declare *processes,*blocks, totalfrags, i, ,j, np,memory,nb
3: Input np //no.of processes
4: Set processes=readProcesses(processes,np)
5: Input memory
6: Input nb //no.of blocks
7: if(nb<np) Then
8: Print “Error message”
9: Return 1
[End If]
10: Set blocks=allocateMemoryBlocks(blocks,nb,memory/nb)
11: Repeat steps 12 to 17 for i=0,j=0 to nb,np step 1
12: Set fragment:=blocks[i]-processes[i]
13: Print processes[i], blocks[i]
14: If(fragment<0) Then : print “Failed”
16: Else: Print fragment
[End If]
17: If(fragment>0) Then: totalfrags+=fragment
[End For]
18: Print “Total fragmentation”,totalfrags
19: Stop
Program:
#include<stdio.h>
main()
VSM COLLEGE OF ENGINEERING Page 29

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

{
int ms,i,ps[20],n,size,p[20],s,intr=0;

printf("Enter size of memory:");


scanf("%d",&ms);
printf("Enter memory for OS:");scanf("%d",&s);
ms-=s;
printf("Enter no.of partitions to be divided:");
scanf("%d",&n);
size=ms/n;
for(i=0;i<n;i++)
{
printf("Enter process and process size:");
scanf("%d%d",&p[i],&ps[i]);
if(ps[i]<=size)
{
intr=intr+size-ps[i];
printf("process%d is allocated\n",p[i]);
}
else
printf("process%d is blocked\n",p[i]);
}
printf("total fragmentation is: %d",intr);
}
Output:

VSM COLLEGE OF ENGINEERING Page 30

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 12

AIM: Simulate the Multiprogramming with a variable number of tasks (MVT)


Description:
Multiprogramming with variable tasks, Paging, Logical to Physical address translation,
Introduces external fragmentation, Compaction, Frames, Page Table, Hardware suppor for
paging. Above mentioned are key points of this lecture handout. Virtual University handout
for introduction to operating system are in detail and explanatory.

Algorithm
Step 1: Start
2: Declare blocks,processes,fragments as pointers
3: Declare i,j,totalfragments:=0,np,nb //i,j for index and np-no.of
processes,nbno.of blocks Input np,nb //no.of processes and no.of blocks
4: Set blocks:=call allocateMemoryBlocks()
5: Set processes:=call allocateProcesses()
6: Set fragments:=allocate with size of no.of processes
7: Repeat Steps 8 to 13 For I:=0 to np step 1 //no.of process times
8: Repeat Steps 9 to 13 For j:=0 to nb step 1 //no.of blocks times
9: If processes[i]<=blocks[j] Then
10: Set fragments[i]:=blocks[j]-processes[i] //allocation and subtraction for
remaining space
11: Set totalfragments+=fragments[i]
12: Print “Fragment #”,i+1,”Size is : “,fragments[i] //Each fragment and its size
13: Exit loop // inner loop only
[End If]
[End For j]
[End For i]
14: Print “Total fragmentation : “,totalfragments
15: Stop

Program:
#include<stdio.h>
main()
{
int i,m,n,tot,s[20];

VSM COLLEGE OF ENGINEERING Page 31

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("Enter total memory size:");scanf("%d",&tot);


printf("Enter no. of pages:");
scanf("%d",&n);
printf("Enter memory for OS:");
scanf("%d",&m);
for(i=0;i<n;i++)
{
printf("Enter size of page%d:",i+1);
scanf("%d",&s[i]);
}
tot=tot-m;
for(i=0;i<n;i++)
{
if(tot>=s[i])
{
printf("Allocate page %d\n",i+1);
tot=tot-s[i];
}
else
printf("process p%d is blocked\n",i+1);
}
printf("External Fragmentation is=%d",tot);

}
Output:

VSM COLLEGE OF ENGINEERING Page 32

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 13

AIM: Simulate Bankers Algorithm for Dead Lock Avoidance.


Description:
 Bankers algorithm is used to detect the occurrence of dead-lock and prevents.
 It from occurrence through the safety algorithm embedded in it which deals with the
information about safe sequence.
 Which when followed creates no problem to the flow of execution of the processes
without any dead-lock occurrence.
 Thus, the efficiency of the CPU increases and for the same reason every CPU is inbuilt
with a banker’s algorithm.

Algorithm: //for Banker's deadlock avoidance


Step 1: Start
2: Declare **Max, **need, **alloc, *avail, *completed, *safeSequence
3: Declare p,r,i,j,count:=0
4: Input p //no.of processes
5: Initialize all Completed[] array to 0 //all are false
6: Input r //no.of resources
7: Set Max:=ProcessRequirement(Max,p,r) //allocate 2-D array and input
8: Set alloc:=ProcessRequirement(alloc,p,r) //allocate 2-D array and input
9: Allocate Avail[] array dynamically
10: Allocate safeSequence[] array dynamically
11: Repeat Step 12 For I:=0 to r step 1
12: Input avail[i]
[End For]
13: Allocate need[][] 2-D array using for loop
14: Repeat step 15,16 for I:=0 to p step 1
15: Repeat step 16 for j:=0 to r step 1
16: Set need[i][j]=Max[i][j]-alloc[i][j]
[End For]
[End For]
17: Call printMatrix(Max,alloc,need,p,r) //for printing of 3-arrays
18: Repeat steps 19-26 For I:=0 to p step 1
19: Repeat step 20-26 for j:=0 to r step 1
20: if(avail[j]>=need[i][j]) then

VSM COLLEGE OF ENGINEERING Page 33

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

21: Set count++


[End If]
22: If(count==r and completed[i]==0) Then
23: Set completed[i]=1 //set true
24: Set safeSequence[i]=i+1
25: Set avail[j]+=alloc[i][j]
26: Set count:=0
[End If]
[End for]
[End for]
27: Repeat Step 28-30 for I:=0 to p step 1
28: If(Completed[i]==0) Then
29: Print “System is unsafe state”
30: Return 1
[End If]
[End For]
31: Print “System is in safe state”
32: Repeat step 33 for I:=0 to p step 1
33: Print safeSequence[i]
[End For]
34: Stop

Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
intMax[10][10],need[10][10],alloc[10][10],avail[10],completed[10],safeSequence[10];
int p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : ");
scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);
VSM COLLEGE OF ENGINEERING Page 34

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("\n\nEnter the Max Matrix for each process : ");


for(i = 0; i < p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}
printf("\n\nEnter the allocation for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)
for(j = 0; j < r; j++)
need[i][j] = Max[i][j] - alloc[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");
for(i = 0; i < p; i++)
{
for( j = 0; j < r; j++)
printf("%d ", Max[i][j]);
printf("\t\t"); for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]); printf("\n");
}
process = -1;
for(i = 0; i < p; i++)
{
if(completed[i] == 0)//if not completed
{
process = i ;
VSM COLLEGE OF ENGINEERING Page 35

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

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


{
if(avail[j] < need[i][j])
{
process = -1; break;
}
}
}
if(process != -1) break;
}
if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != p && process != -1);
if(count == p)
{
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else printf("\nThe system is in an unsafe state!!");
}

VSM COLLEGE OF ENGINEERING Page 36

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment -14

AIM: Simulate Bankers Algorithm for Dead Lock Prevention.


Description:
Havened in his pioneering work showed that since all four of the conditions are
necessary for deadlock to occur, it follows that deadlock might be prevented by denying any
one of the conditions.
Elimination of “Mutual Exclusion” Condition
Elimination of “Hold and Wait” Condition
Elimination of “No-preemption” Condition
Elimination of “Circular Wait” Condition

Algorithm: //for Banker's deadlock prevention


Step 1: Start
2: Declare **Max, **need, **alloc, *avail, *completed, *safeSequence
3: Declare p,r,i,j,count:=0
4: Input p //no.of processes
5: Initialize all Completed[] array to 0 //all are false
6: Input r //no.of resources
7: Set Max:=ProcessRequirement(Max,p,r) //allocate 2-D array and input
8: Set alloc:=ProcessRequirement(alloc,p,r) //allocate 2-D array and input
9: Allocate Avail[] array dynamically
10: Allocate safeSequence[] array dynamically
11: Repeat Step 12 For I:=0 to r step 1
12: Input avail[i]
[End For]
13: Allocate need[][] 2-D array using for loop
14: Repeat step 15,16 for I:=0 to p step 1
15: Repeat step 16 for j:=0 to r step 1
16: Set need[i][j]=Max[i][j]-alloc[i][j]
[End For]
[End For]
17: Call printMatrix(Max,alloc,need,p,r) //for printing of 3-arrays
18: Repeat steps 19-26 For I:=0 to p step 1
19: Repeat step 20-26 for j:=0 to r step 1
20: if(avail[j]>=need[i][j]) then
21: Set count++
[End If]
22: If(count==r and completed[i]==0) Then
23: Set completed[i]=1 //set true
24: Set safeSequence[i]=i+1
VSM COLLEGE OF ENGINEERING Page 37

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

25: Set avail[j]+=alloc[i][j]


26: Set count:=0
[End If]
[End for]
[End for]
27: Repeat Step 28-30 for I:=0 to p step 1
28: If(Completed[i]==0) Then

29: Print “System is unsafe state”


30: Return 1
[End If]
[End For]
31: Print “System is in safe state”
32: Repeat step 33 for I:=0 to p step 1
33: Print safeSequence[i]
[End For]
34: Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int allocated[15][15],max[15][15],need[15][15],avail[15],tres[15],work[15],flag[15];
int pno,rno,i,j,prc,count,t,total;
count=0; //clrscr();
printf("\n Enter number of process:");
scanf("%d",&pno);
printf("\n Enter number of resources:");
scanf("%d",&rno);
for(i=1;i<=pno;i++)
{
flag[i]=0;
}
printf("\n Enter total numbers of each resources:");
for(i=1;i<= rno;i++) scanf("%d",&tres[i]);
printf("\n Enter Max resources for each process:");
for(i=1;i<= pno;i++)
VSM COLLEGE OF ENGINEERING Page 38

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&max[i][j]);
}
printf("\n Enter allocated resources for each process:");
for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&allocated[i][j]);
}
printf("\n available resources:\n");
for(j=1;j<= rno;j++) {
avail[j]=0; total=0;
for(i=1;i<= pno;i++)
{
total+=allocated[i][j];
}
avail[j]=tres[j]-total;
work[j]=avail[j];
printf(" %d \t",work[j]);
}
do
{
for(i=1;i<= pno;i++)
{
for(j=1;j<= rno;j++)
{
need[i][j]=max[i][j]-allocated[i][j];
}
}
printf("\n Allocated matrix Max need");
for(i=1;i<= pno;i++)
{
printf("\n");
VSM COLLEGE OF ENGINEERING Page 39

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

for(j=1;j<= rno;j++)
{
printf("%4d",allocated[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",max[i][j]);
}
printf("|"); for(j=1;j<= rno;j++)
{
printf("%4d",need[i][j]);
}
}
prc=0; for(i=1;i<= pno;i++)
{
if(flag[i]==0)
{
prc=i; for(j=1;j<= rno;j++)
{
if(work[j]< need[i][j])
{
prc=0; break;
}
}
}
if(prc!=0) break;
} if(prc!=0)
{
printf("\n Process %d completed",i);
count++; printf("\n Available matrix:");
for(j=1;j<= rno;j++)
{
work[j]+=allocated[prc][j];
allocated[prc][j]=0; max[prc][j]=0; flag[prc]=1; printf(" %d",work[j]);
}
VSM COLLEGE OF ENGINEERING Page 40

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

}
}
while(count!=pno&&prc!=0);
if(count==pno)
printf("\nThe system is in a safe state!!");
else printf("\nThe system is in an unsafe state!!");
getch();
}

VSM COLLEGE OF ENGINEERING Page 41

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

FILE ALLOCATION STRATEGIES


Experiment - 15

AIM: Simulate the page replacement algorithm FIFO


Description:
 The simplest page-replacement algorithm is a FIFO algorithm. The first-in, first-out
(FIFO) page replacement algorithm is a low-overhead algorithm that requires little
bookkeeping on the part of the operating system.

 The idea is obvious from the name – the operating system keeps track of all the pages
in memory in a queue, with the most recent arrival at the back, and the oldest arrival in
front. When a page needs to be replaced, the page at the front of the queue (the oldest
page) is selected.

 While FIFO is cheap and intuitive, it performs poorly in practical application. Thus, it
is rarely used in its unmodified form.

Algorithm:

Step 1: Start
Step 2: Declare frame, available, count=0, n //n for number of pages
Step 3: Enter pages
Step 4: Enter page numbers
Step 5: Enter number of frames
Step 6: Print pages
Step 7: Print page numbers
Step 8: Print number of frames
Step 9: Print reference string, page frames
Step 10: count no of page faults
Step 11: print pagefaults
Step 12: stop
Program:
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("ENTER THE NUMBER OF PAGES:");
scanf("%d",&n);
VSM COLLEGE OF ENGINEERING Page 42

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("\nENTER THE PAGE NUMBER :");


for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\nENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\t ref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
}

VSM COLLEGE OF ENGINEERING Page 43

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 16

AIM: Simulate the page replacement algorithm LRU


Description:
 If the optimal algorithm is not feasible, perhaps an approximation of the optimal
algorithm is possible.
 The key distinction between the FIFO and OPT algorithms (other than looking
backward versus forward in time) is that the FIFO algorithm uses the time when a page
was brought into memory,
 Whereas the OPT algorithm uses the time when a page is to be used.
 If we use the recent past as an approximation of the near future, then we can replace the
page that has not been used for the longest period of time.
 This approach is the least-recently -used(LRU) algorithm
Algorithm:
Step 1: Start
Step 2: Declare frame, available, count=0, n //n for number of pages
Step 3: Enter pages
Step 4: Enter page numbers
Step 5: Enter number of frames
Step 6: Print pages
Step 7: Print page numbers
Step 8: Print number of frames
Step 9: Print reference string, page frames
Step 10: count no of page faults
Step 11: print page faults
Step 12: stop
Program:
#include<stdio.h>
main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("\nEnter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
VSM COLLEGE OF ENGINEERING Page 44

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("\nEnter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
VSM COLLEGE OF ENGINEERING Page 45

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);
}

VSM COLLEGE OF ENGINEERING Page 46

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 17

AIM: Simulate the page replacement algorithm LFU.


Description:
 The least frequently used (LFU) page-replacement algorithm requires that the page
with the smallest count be replaced.
 The reason for this selection is that an actively used page should have a large reference
count.
 A problem arises, however, when a page is used heavily during the initial phase of a
process but then is never used again.
 Since it was used heavily, it has a large count and remains in memory even though it is
no longer needed.
 One solution is to shift the counts right by 1 bit at regular intervals, forming an
exponentially decaying average usage count.
Algorithm:
Step 1: Start
Step 2: Declare frame, available, count=0, n //n for number of pages
Step 3: Enter pages
Step 4: Enter page numbers
Step 5: Enter number of frames
Step 6: Print pages
Step 7: Print page numbers
Step 8: Print number of frames
Step 9: Print reference string, page frames
Step 10: count no of page faults
Step 11: print pagefaults
Step 12: stop
Program:
#include<stdio.h>
main()
{
int fr[5],i,j,k,t[5],p=1,flag=0,page[25],psz,nf,t1,u[5];
printf("Enter the number of frames:");
scanf("%d",&nf);
printf("Enter the page size");
scanf("%d",&psz);
VSM COLLEGE OF ENGINEERING Page 47

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("Enter the page sequence:");


for(i=1; i<=psz; i++)
scanf("%d",&page[i]);
for(i=1; i<=nf; i++)
fr[i]=-1;
for(i=1; i<=psz; i++)
{
if(full(fr,nf)==1)
break;
else
{
flag=0;
for(j=1; j<=nf; j++)
{
if(page[i]==fr[j])
{
flag=1;
printf(" \t%d:\t",page[i]);
break;
}
}
if(flag==0)
{
fr[p]=page[i];
printf(" \t%d:\t",page[i]);
p++;
}
for(j=1; j<=nf; j++)
printf(" %d ",fr[j]);
printf("\n");
}
}
p=0;
for(; i<=psz; i++)
{
flag=0;
VSM COLLEGE OF ENGINEERING Page 48

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

for(j=1; j<=nf; j++)


{
if(page[i]==fr[j])
{
flag=1;
break;
}
}
if(flag==0)
{
p++;
for(j=1; j<=nf; j++)
{
for(k=i+1; k<=psz; k++)
{
if(fr[j]==page[k])
{
u[j]=k;
break;
}
else
u[j]=21;
}
}
for(j=1; j<=nf; j++)
t[j]=u[j];
for(j=1; j<=nf; j++)
{
for(k=j+1; k<=nf; k++)
{
if(t[j]<t[k])
{
t1=t[j];
t[j]=t[k];
t[k]=t1;
}
VSM COLLEGE OF ENGINEERING Page 49

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

}
}
for(j=1; j<=nf; j++)
{
if(t[1]==u[j])
{
fr[j]=page[i];
u[j]=i;
}
}
printf("page fault\t");
}
else
printf(" \t");
printf("%d:\t",page[i]);
for(j=1; j<=nf; j++)
printf(" %d ",fr[j]);
printf("\n");
}
printf("\ntotal page faults: %d",p+3);
// getch();
}
int full(int a[],int n)
{
int k;
for(k=1; k<=n; k++)
{
if(a[k]==-1)
return 0;
}
return 1;
}

VSM COLLEGE OF ENGINEERING Page 50

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 18

AIM: Simulate the Sequenced File allocation strategies.


Description:
Sequential file allocation strategy: In this type of strategy, the files are allocated in a
sequential manner such that there is continuity among the various parts or fragments of the
file.
Algorithm:
Step 1: Start
2: Declare I
3: Repeat step 4 to 10 for i=0 to n step 1
4: Input files[i].filename
5: Repeat 6-8 While True
6: Input files[i].startBlock
7: If(!isBlockOccupied(files,i,files[i].startBlock) break;
8: print “Sorry!starting block is already occupied, try again\n”
[End While]
9: Repeat 10 to 13 While True
10: Input files[i].size
11: Set files[i].endBlock=files[i].startBlock+files[i].size
12: if(!isBlockOccupied(files,i,files[i].endBlock)) break;
13: Print “Sorry! Ending block range is collaged, try again\n”
[End While]
[End For]
14: Return files
15: Stop
Program:
#include<stdio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],x,b[20][20];

printf("Enter no.of files:");


scanf("%d",&n);
for(i=0;i<n;i++)
{

VSM COLLEGE OF ENGINEERING Page 51

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("Enter the starting block and size of file%d:",i+1);


scanf("%d%d",&sb[i],&s[i]);
printf("Enter the blocks occupied by file%d:",i+1);
scanf("%d",&m[i]);
printf("enter blocks of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
}
printf("File\tIndex\tlength\n");
for(i=0;i<n;i++)
printf("%d\t %d \t%d\n",i+1,sb[i],m[i]);
printf("Enter file name:");
scanf("%d",&x);
printf("File name is:%d\n",x);
i=x-1;
printf("length is:%d",sb[i]);
printf("Block occupied are:");
for(j=0;j<m[i];j++)
printf("%3d",b[i][j]);

VSM COLLEGE OF ENGINEERING Page 52

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 19

AIM: Simulate the Indexed File allocation strategies.


Description:
Indexed file allocation strategy: In this type of strategy, the files are allocated based on
the indexes that are created for each fragment of the file such that each and every similar
indexed file is maintained by the primary index thereby providing flow to the file fragments.
Algorithm:
Step 1: Start
2: Declare i
3: Repeat 4-10 for i:=0 to n step 1
4: Input files[i].filename
5: Repeat 6-8 While(true)
6: Input files[i].indexBlock
7: if(!isIndexBlockOccupied(files,i,files[i].indexBlock) AND
!isChildBlockOccupied(files,i,files[i].indexBlock)) break;
8: Print “Error”
[End While]
9: Input files[i].noofChildBlocks
10: files[i].childBlocks=allocateChildBlocks(files,i,files[i].noOfChildBlocks)
[End For]
11: Return files
12: Stop

Program:
#include<stdio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],b[20][20],x;

printf("Enter no. of files:");


scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter starting block and size of file%d:",i+1);
scanf("%d%d",&sb[i],&s[i]);

VSM COLLEGE OF ENGINEERING Page 53

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

printf("Enter blocks occupied by file%d:",i+1);


scanf("%d",&m[i]);
printf("enter blocks of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
}
printf("\nFile\t index\tlength\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);
}
printf("\nEnter file name:");
scanf("%d",&x);
printf("file name is:%d\n",x);
i=x-1;
printf("Index is:%d",sb[i]);
printf("Block occupied are:");
for(j=0;j<m[i];j++)
printf("%3d",b[i][j]);
}

VSM COLLEGE OF ENGINEERING Page 54

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

Experiment - 20

AIM: Simulate the Linked File allocation strategies.


Description:
Linked file allocation strategy: In this type of strategy, the files are allocated in a linked
list format where each and every fragment is linked to the other file through either addresses
or pointers. Thus, the starting location of the file servers for the purpose of extraction of the
entire file because every fragment is linked to each other.
Algorithm
1: Start
2: Declare I
3: Repeat step 4 to 10 for i=0 to n step 1
4: Input files[i].filename
5: Repeat 6-8 While True
6: Input files[i].startBlock
7: If(!isBlockOccupied(files,i,files[i].startBlock) break;
8: print “Sorry!starting block is already occupied, try again\n”
[End While]
9: Repeat 10 to 13 While True
10: Input files[i].size
11: Set files[i].endBlock=files[i].startBlock+files[i].size
12: if(!isBlockOccupied(files,i,files[i].endBlock)) break;
13: Print “Sorry! Ending block range is collaged, try again\n”
[End While]
[End For]
11: Return files
12: Stop
Program:
#include<stdio.h>

struct file
{
char fname[10];
int start,size,block[10];
}f[10];
main()

VSM COLLEGE OF ENGINEERING Page 55

Downloaded by Rajkumar V ([email protected])


lOMoARcPSD|54868014

{
int i,j,n;

printf("Enter no. of files:");scanf("%d",&n);


for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);
}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);
for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d--->",f[i].block[j]);
printf("\n");
}

VSM COLLEGE OF ENGINEERING Page 56

Downloaded by Rajkumar V ([email protected])

You might also like