Os Lab Manual
Os Lab Manual
OS LAB Manual
LAB MANUAL
OPERATING SYSTEMS
II B.TECH I SEM
(JNTUK)
(R20)
COMPUTER SCIENCE AND ENGINEERING
V S M COLLEGE OF ENGINEERING
RAMCHANDRAPURAM
INDEX
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)
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
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:
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
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
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
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
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);
Experiment-3
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
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);
}
Experiment-5
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:”);
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
x--;
mutex=signal(mutex);
}
Experiment-6
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);
}
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);
}
exit(EXIT_SUCCESS);
}
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
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
}
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;
}
Experiment -8
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;
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);
}
Experiment -9
[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;
}
Experiment -10
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++)
{
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;
}
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
{
int ms,i,ps[20],n,size,p[20],s,intr=0;
Experiment - 12
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];
}
Output:
Experiment - 13
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
Experiment -14
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
{
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
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
}
}
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();
}
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
Experiment - 16
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
}
}
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);
}
Experiment - 17
}
}
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;
}
Experiment - 18
Experiment - 19
Program:
#include<stdio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],b[20][20],x;
Experiment - 20
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
main()
{
int i,j,n;