0% found this document useful (0 votes)
3 views70 pages

Cy cb3402 Lab Manual

The document provides an overview of basic Unix commands, including general, directory, and file commands, along with examples of their usage. It also covers the fork, wait, and exec system calls in process management, detailing the algorithms and sample programs for creating and managing child processes. The execution results demonstrate the successful implementation of these commands and system calls.
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)
3 views70 pages

Cy cb3402 Lab Manual

The document provides an overview of basic Unix commands, including general, directory, and file commands, along with examples of their usage. It also covers the fork, wait, and exec system calls in process management, detailing the algorithms and sample programs for creating and managing child processes. The execution results demonstrate the successful implementation of these commands and system calls.
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/ 70

BASICS OF UNIX COMMANDS

EX NO: 1

Aim
To study and execute Unix commands.
Unix is security conscious, and can be used only by those persons who have an account.
Telnet (Telephone Network) is a Terminal emulator program for TCP/IP networks that enables users
to log on to remote servers.
To logon, type telnet server ip address in run window.
User has to authenticate himself by providing username and password. Once verified, a greeting and $
prompt appears. The shell is now ready to receive commands from the user.
Options suffixed with a hyphen (–) and arguments are separated by space.
General commands
Command Function
date Used to display the current system date and time.
date +%D Displays date only
date +%T Displays time only
date +% Y Displays the year part of date
date +% H Displays the hour part of time
cal Calendar of the current month
calyear Displays calendar for all months of the specified year
calmonth year Displays calendar for the specified month of the year
who Login details of all users such as their IP, Terminal No, User name,
who am i Used to display the login details of the user
tty Used to display the terminal name
uname Displays the Operating System
uname –r Shows version number of the OS (kernel).
uname –n Displays domain name of the server
echo "txt" Displays the given text on the screen
echo $HOME Displays the user's home directory
bc Basic calculator. Press Ctrl+dto quit
lpfile Allows the user to spool a job along with others in a print queue.
man cmdname Manual for the given command. Press q to exit
history To display the commands used by the user since log on.
exit Exit from a process. If shell is the only process then logs out
Directory commands
Command Function
pwd Path of the present working directory
mkdirdir A directory is created in the given name under the current

1
directory
mkdirdir1 dir2 A number of sub-directories can be created under one stroke
cd subdir Change Directory. If the subdirstarts with / then path starts from
root (absolute) otherwise from current working directory.
cd To switch to the home directory.
cd / To switch to the root directory.
cd.. To move back to the parent directory
rmdirsubdir Removes an empty sub-directory.

File commands
Command Function
cat >filename To create a file with some contents. To end typing press Ctrl+d.
The >symbol means redirecting output to a file. (<for input)
cat filename Displays the file contents.
cat >>filename Used to append contents to a file
cpsrc des Copy files to given location. If already exists, it will be overwritten
cp –i src des Warns the user prior to overwriting the destination file
cp –r src des Copies the entire directory, all its sub-directories and files.
mv old new To rename an existing file or directory. –i option can also be used
mv f1 f2 f3 dir To move a group of files to a directory.
mv –v old new Display name of each file as it is moved.
rmfile Used to delete a file or group of files. –i option can also be used
rm * To delete all the files in the directory.
rm –r * Deletes all files and sub-directories
rm –f * To forcibly remove even write-protected files
ls Lists all files and subdirectories (blue colored) in sorted manner.
lsname To check whether a file or directory exists.
lsname* Short-hand notation to list out filenames of a specific pattern.
ls –a Lists all files including hidden files (files beginning with .)
ls –x dirname To have specific listing of a directory.
ls –R Recursive listing of all files in the subdirectories
ls –l Long listing showing file access rights (read/write/execute-rwxfor
user/group/others-ugo).
cmpfile1 file2 Used to compare two files. Displays nothing if files are identical.
wcfile It produces a statistics of lines (l), words(w), and characters(c).
chmodperm file Changes permission for the specified file. (r=4, w=2, x=1)
chmod 740 file sets all rights for user, read only for groups
and no rights for others

2
Output:
GENERAL COMMANDS
[student@vecit ~]$ date
Mon Dec 15 10:12:47 AQTT 2014
[student@vecit ~]$ date +%D
12/15/14
[student@vecit ~]$ date +%T
10:13:11
[student@vecit ~]$ date +%Y
2014
[student@vecit ~]$ date +%H
10

3
[student@vecit ~]$ who
studentpts/1 Dec 15 10:05 (172.16.1.14)
[student@vecit ~]$ who am i
studentpts/1 Dec 15 10:05 (172.16.1.14)
[student@vecit ~]$ tty
/dev/pts/1
[student@vecit ~]$ uname
Linux
[student@vecit ~]$ echo "hello"
hello
[student@vecit ~]$ echo $HOME
/home/student
[student@vecit ~]$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation,
Inc. This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
[student@vecit ~]$ man lp
lp(1) Easy Software Products lp(1)
NAME
lp - print files
cancel - cancel jobs
SYNOPSIS
lp [ -E ] [ -c ] [ -d destination ] [ -h server ] [ -m ] [ -n num-
copies [ -o option ] [ -q priority ] [ -s ] [ -t title ] [ -H handling
] [ -P page-list ] [ file(s) ]
lp [ -E ] [ -c ] [ -h server ] [ -i job-id ] [ -n num-copies [ -o
option ] [ -q priority ] [ -t title ] [ -H handling ] [ -P page-list ]
cancel [ -a ] [ -h server ] [ -u username ] [ id ] [ destination ] [
destination-id ]
DESCRIPTION
lpsubmits files for printing or alters a pending job. Use a filename of "-" to force printing from the
standard input.
cancelcancels existing print jobs. The -a option will remove all jobs
from the specified destination.

OPTIONS
The following options are recognized by lp:
[student@vecit ~]$ history
1 ls
2 date
3 date +%D
4 date +%T
5 date +%Y
6 date +%H
7 cal
8 cal 2014
9 cal 5 2014

4
10 who
11 who am i
12 tty
13 uname
14 uname -r
15 uname -n
16 echo "hi"
17 echo $HOME
18 bc
19 manlp
20 history
21 PWD
22 pwd
23 mkdir san
24 mkdir san s
25 mkdir s1 s2
26 ls
27 cd s1
28 cd
29 cd /
30 cd..
31 cd . .
32 rmdir s
33 rmdir s1
34 ls
35 cd
36 ls
37 rmdir s1
38 ls
39 CAT>TEST
40 cat>test
41 cat test
42 cat>>test
43 cat test
44 cat test1
45 cat>test1
46 cp test test1
47 cat test1
48 exit
49 vi
50 vi swap.sh
51 sh swap
52 cc swap.sh
53 cc swap
54 sh swap.sh
55 vi swap.sh
56 sh swap.sh
57 vi swap.sh
58 sh swap.sh

5
59 vi temp.sh
60 sh temp.sh
61 vi temp.sh
62 sh temp.sh
63 vi temp.sh
64 sh temp.sh
65 vi temp.sh
66 sh temp.sh
67 exit
68 date
69 date + %D
70 date +%D
71 date +%T
72 date +% Y
73 exit
74 date
75 date +%D
76 date +%T
77 date +%Y
78 date +%H
79 cal
80 cal 2014
81 cal may 2014
82 cal 5 2014
83 who
84 who am i
85 tty
86 uname
87 echo "hello"
88 echo $HOME
89 bc
90 lp swap
91 manlp
92 history
DIRECTORY COMMANDS
[student@vecit ~]$ pwd
/home/student
[student@vecit ~]$ mkdir san
[student@vecit ~]$ mkdir s1 s2
[student@vecit ~]$ ls
s s1 s2 san
[student@vecit ~]$ cd s1
[student@vecit s1]$ cd
[student@vecit ~]$ cd /
[student@vecit /]$ cd . .
[student@vecit /]$ rmdir s1

[student@vecit ~]$ ls

6
s s2 san
[student@vecit ~]$

[student@vecit ~]$ cat>test


hi welcome operating systems lab
[student@vecit ~]$ cat test
hi welcome operating systems lab [student@vecit ~]$ cat>>test fourth semester
[student@vecit ~]$ cat test

FILE COMMANDS
hi welcome operating systems lab fourth semester
[student@vecit ~]$ cat>test1
[student@vecit ~]$ cp test test1
[student@vecit ~]$ cat test1
hi welcome operating systems lab fourth semester
[student@vecit ~]$ cp -i test test1
cp: overwrite `test1'? y
[student@vecit ~]$ cp -r test test1
[student@vecit ~]$ ls
s s2 san swap.sh temp.sh test TEST test1
[student@vecit ~]$ mv san san1
[student@vecit ~]$ ls
s s2 san1 swap.sh temp.sh test TEST test1
[student@vecit ~]$ mv test test1 san1
[student@vecit ~]$ mv -v san1 sannew
`san1' -> `sannew'
[student@vecit ~]$ ls
s s2sannew swap.sh temp.sh TEST
[student@vecit ~]$ cmp test test1
cmp: test: No such file or directory

Result:
Thus the study and execution of Unix commands has been completed successfully.

7
EX NO: 2A
Fork system call

Aim:
To create a new child process using fork system call.

Algorithm:
1. Declare a variable x to be shared by both child and parent.
2. Create a child process using fork system call.
3. If return value is -1 then
a. Print "Process creation unsuccessfull"
b. Terminate using exit system call.
4. If return value is 0 then
a. Print "Child process"
b. Print process id of the child using getpid system call
c. Print value of x
d. Print process id of the parent using getppid system call
5. Otherwise
a. Print "Parent process"
b. Print process id of the parent using getpid system call
c. Print value of x
d. Print process id of the shell using getppid system call.
6. Stop

Program:
/* Process creation - fork.c */

#include <stdio.h> #include


<stdlib.h> #include <unistd.h>
#include <sys/types.h> main()
{
pid_t pid; int x =
5; pid = fork();
x++;
if (pid < 0)
{
printf("Process creation error"); exit(-
1);
}
else if (pid == 0)

8
{
printf("Child process:"); printf("\nProcess id is %d",
getpid()); printf("\nValue of x is %d", x);
printf("\nProcess id of parent is %d\n", getppid());
}
else
{
printf("\nParent process:"); printf("\nProcess id is %d",
getpid()); printf("\nValue of x is %d", x);
printf("\nProcess id of shell is %d\n", getppid());
}
}

Output:
$ gcc fork.c

$ ./a.out Child
process:
Process id is 19499 Value of x is
6
Process id of parent is 19498 Parent process:
Process id is 19498
Value of x is 6
Process id of shell is 3266

Result:
Thus a child process is created with copy of its parent's address space.

9
EX NO: 2B
wait system call

Aim:
To block a parent process until child completes using wait system call.

Algorithm:

1. Create a child process using fork system call.


2. If return value is -1 then
a. Print "Process creation unsuccessfull"
3. Terminate using exit system call.
4. If return value is > 0 then
a. Suspend parent process until child completes using wait system call
b. Print "Parent starts"
c. Print even numbers from 0–10
d. Print "Parent ends"
5. If return value is 0 then
a. Print "Child starts"
b. Print odd numbers from 0–10
c. Print "Child ends"
6. Stop

Program:
/* Wait for child termination - wait.c */

#include <stdio.h> #include


<stdlib.h> #include <unistd.h>
#include <sys/types.h> #include
<sys/wait.h>
main()
{
int i, status; pid_t
pid; pid = fork(); if
(pid < 0)
{
printf("\nProcess creation failure\n"); exit(-1);
}
else if(pid > 0)
{
wait(NULL);
printf ("\nParent starts\nEven Nos: "); for

10
(i=2;i<=10;i+=2)
printf ("%3d",i); printf ("\nParent
ends\n");
}
else if (pid == 0)
{
printf ("Child starts\nOdd Nos: "); for
(i=1;i<10;i+=2)
printf ("%3d",i); printf ("\nChild
ends\n");
}
}

Output:

$ gcc wait.c

$ ./a.out Child
starts
Odd Nos: 1 3 5 7 9
Child ends
Parent starts
Even Nos: 2 4 6 8 10
Parent ends

Result:
Thus using wait system call zombie child processes were avoided.

11
EX NO: 2C
exec system call

Aim:
To load an executable program in a child processes exec system call.

Algorithm:

1. If no. of command line arguments 3 then stop.


2. Create a child process using fork system call.
3. If return value is -1 then
a. Print "Process creation unsuccessfull"
b. Terminate using exit system call.
4. If return value is > 0 then
a. Suspend parent process until child completes using wait system call
b. Print "Child Terminated".
c. Terminate the parent process.
5. If return value is 0 then
a. Print "Child starts"
b. Load the program in the given path into child process using exec system call.
c. If return value of exec is negative then print the exception and stop.
d. Terminate the child process.
6. Stop

Program:

/* Load a program in child process - exec.c */

#include <stdio.h> #include


<sys/types.h> #include
<unistd.h> #include <stdlib.h>
main(int argc, char*argv[])
{
pid_t pid; int
i;
if (argc != 3)
{
printf("\nInsufficient arguments to load program"); printf("\nUsage: ./a.out
<path> <cmd>\n"); exit(- 1);
}

12
switch(pid = fork())
{
case -1:
printf("Fork failed"); exit(-
1);
case 0:
printf("Child process\n"); i =
execl(argv[1], argv[2], 0); if (i < 0)
{
printf("%s program not loaded using exec system call\n", argv[2]);
exit(-1);
}
default:
wait(NULL); printf("Child
Terminated\n"); exit(0);
}
}

13
Output:
$ gcc exec.c

$ ./a.out

Insufficient arguments to load program Usage: ./a.out <path>


<cmd>
$ ./a.out /bin/ls ls Child process
a.out cmdpipe.c consumer.c
dirlist.c ex6a.c ex6b.c
ex6c.c ex6d.c exec.c
fappend.c fcfs.c fcreate.c
fork.c fread.c hello
list list.c pri.c
producer.c rr.c simls.c
sjf.c stat.c wait.c
Child Terminated
$ ./a.out /bin/who who
Child process
who program not loaded using exec system call Child Terminated
$ ./a.out /usr/bin/who who Child
process
vijai pts/0 2013-04-24 15:48 (192.168.144.1) Child
Terminated

Result:
Thus the child process loads a binary executable file into its address space.

14
EX NO: 2D
stat system call

Aim:
To display file status using stat system call.

Algorithm:

1. Get filename as command line argument.


2. If filename does not exist then stop.
3. Call stat system call on the filename that returns a structure
4. Display members st_uid, st_gid, st_blksize, st_block, st_size, st_nlink, etc.,
5. Convert time members such as st_atime, st_mtime into time using ctime function
6. Compare st_mode with mode constants such as S_IRUSR, S_IWGRP,
S_IXOTH and display file permissions.
7. Stop

Program:
/* File status - stat.c
*/ #include <stdio.h> #include
<sys/stat.h> #include <stdlib.h>
#include <time.h>
int main(int argc, char*argv[])
{
struct stat file; int n;
if (argc != 2)
{
printf("Usage: ./a.out
<filename>\n"); exit(-1);
}
if ((n = stat(argv[1], &file)) == -1)
{
perror(argv[1]);
exit(-1);
}
printf("User id : %d\n", file.st_uid); printf("Group id : %d\n",
file.st_gid); printf("Block size : %d\n", file.st_blksize); printf("Blocks
allocated : %d\n", file.st_blocks); printf("Inode no. : %d\n", file.st_ino);
printf("Last accessed : %s", ctime(&(file.st_atime))); printf("Last modified :
%s", ctime(&(file.st_mtime))); printf("File size : %d bytes\n", file.st_size);
printf("No. of links : %d\n", file.st_nlink);
printf("Permissions : ");
printf( (S_ISDIR(file.st_mode)) ? "d" : "-");

15
printf( (file.st_mode & S_IRUSR) ? "r" : "-");
printf( (file.st_mode & S_IWUSR) ? "w" : "-");
printf( (file.st_mode & S_IXUSR) ? "x" : "-");
printf( (file.st_mode & S_IRGRP) ? "r" : "-");
printf( (file.st_mode & S_IWGRP) ? "w" : "-");
printf( (file.st_mode & S_IXGRP) ? "x" : "-");
printf( (file.st_mode & S_IROTH) ? "r" : "-");
printf( (file.st_mode & S_IWOTH) ? "w" : "-");
printf( (file.st_mode & S_IXOTH) ? "x" : "-"); printf("\n");
if(file.st_mode & S_ IFREG) printf("File type :
Regular\n");
if(file.st_mode & S_ IFDIR) printf("File type :
Directory\n");
}

Output:
$ gcc stat.c

$ ./a.out fork.c User id :


0 Group id : 0 Block
size
: 4096
Blocks allocated :
8 Inode no. : 16627
Last accessed : Fri Feb 22 21:57:09 2013 Last modified :
Fri Feb 22 21:56:13 2013 File size : 591 bytes
No. of links : 1 Permissions : -rw-
r--r-
- File type : Regular

Result:
Thus attributes of a file is displayed using stat system call.

16
EX NO: 2E
readdir system call

Aim:
To display directory contents using readdir system call.

Algorithm:

1. Get directory name as command line argument.


2. If directory does not exist then stop.
3. Open the directory using opendir system call that returns a structure
4. Read the directory using readdir system call that returns a structure
5. Display d_name member for each entry.
6. Close the directory using closedir system call.
7. Stop
Program:
/* Directory content listing - dirlist.c */

#include <stdio.h> #include


<dirent.h> #include <stdlib.h>
main(int argc, char *argv[])
{
struct dirent
*dptr; DIR *dname; if
(argc != 2)
{
printf("Usage: ./a.out
<dirname>\n"); exit(-1);
}
if((dname = opendir(argv[1])) == NULL)
{
perror(argv[1]);
exit(-1);
}
while(dptr=readdir(dname)) printf("%s\n", dptr-
>d_name);
closedir(dname);
}

17
Output:
$ gcc dirlist.c

$ ./a.out
vijai wait.c
a.out
..
stat.c
dirlist.c
fork.c
.
exec.c

Result:
Thus files and subdirectories in the directory was listed that includes hidden files.

18
Ex IMPLEMENTATION OF ROUND ROBIN SCHEDULING
No:3A ALGORITHM

Aim
To write a C program to implement Round Robin scheduling algorithm.

Algorithm:
Step 1: Start the program.
Step 2: Get the input process and their burst
time. Step 3: Sort the processes based on
priority.
Step 4: Compute the waiting time and turnaround time for each
process. Step 5: Calculate the average waiting time and average
turnaround time. Step 6: Print the details about all the processes.
Step 7: Stop the program.

Program:
#include<s
tdio.h>
#include<c
onio.h>
voidmain()
{
intct=0,y[30],j=0,bt[10],cwt=0;
inttq,i,max=0,n,wt[10],t[10],at[10],tt[10
],b[10]; float a=0.0,s=0.0;
char
p[10]
[10];
clrscr();
printf("\n enter the no of
process:"); scanf("%d",&n);
printf("\nenter the time
quantum");
scanf("%d",&tq);
printf("\nenter the process name,bursttime,arrival time");
for(i=0;i<n;i++)
{
scanf("%s",p[i]);
scanf("%d",&bt[i]);
scanf("%d",&a
t[i]);
wt[i]=t[i]=0;
b[i]=bt[i];
}

19
printf("\n\t\tGANTT CHART");
printf("\n \n");
for(i=0;i<n;i++)
{
if(max<bt[i])
max=bt[i];
}
while(max!=0)
{
for(i=0;i<n;i++)
{
if(bt[i]>0)
{
if(ct==0) wt[i]=wt[i]+cwt; else
wt[i]=wt[i]+(cwt-t[i]);
}
if(bt[i]==0) cwt=cwt+0;
else if(bt[i]==max)
{
if(bt[i]>tq)
{
cwt=cwt+tq;
bt[i]=bt[i]-tq;
max=max-tq;
}
else
{
cwt=cwt+bt[i];
bt[i]=0; max=0;
}
printf("|\t%s",p[i]);
y[j]=cwt;
j++;
}
else if(bt[i]<tq)
{
cwt=cwt+bt[i];
bt[i]=0; printf("|\t
%s",p[i]); y[j]=cwt;
j++;
}
else if(bt[i]>tq)
{
cwt=cwt+tq;
bt[i]=bt[i]-tq;
printf("|\t%s",p[i]);
y[j]=cwt;
j++;

20
}
else if(bt[i]==tq)
{
cwt=cwt+bt[i];
printf("|\t%s",p[i]);
bt[i]=0;
y[j]=cwt;
j++;
}
t[i]=cwt;
}
ct=ct+1;
}
for(i=0;i<n;i++)
{
wt[i]=wt[i]-at[i];
a=a+wt[i]; tt[i]=wt[i]
+b[i]; s=s+tt[i];
}
a=a/n;
s=s/n;
printf("\n ");
printf("\n0");
for(i=0;i<j;i++)
printf("\t%d",y[i]);
printf("\n");
printf("\n ");
printf("\n\t\t ROUND ROBIN\n");
printf("\n Process Burst-time Arrival-time Waiting-time Turnaround-time\n"); for(i=0;i<n;i+
+)
printf("\n\n %d%s \t %d\t\t %d \t\t %d\t\t %d",i+1,p[i],b[i],at[i],wt[i],tt[i]);
printf("\n\nAvg waiting time=%f",a);
printf("\n\nAvgturn around time=%f",s);
getch();
}

21
Output:
enter the no of process:3
enter the time quantum2
enter the process name,bursttime,arrival time
p1 2 0
p2 3 1
p3 4 2
GANTT CHART

| p1| p2| p3| p2| p3

0 2 4 6 7 9

ROUND ROBIN
Process Burst-time Arrival-time Waiting-time Turnaround-time
1p1 2 0 0 2
2p2 3 1 3 5
3p3 4 2 3 5
Avg Waiting Time=2.000000
Avg Turnaround Time=4.000000

Result:
The Round Robin scheduling algorithm has been implemented in C.

22
Ex No: 3B
IMPLEMENTATION OF SJF SCHEDULING ALGORITHM

Aim
To write a C program to implement shortest job first (non-pre-emptive) scheduling algorithm.

Description:
Assume the next burst time of each process is known. SJF selects process which has the shortest
burst time. This is an Optimal algorithm because it has the shortest average waiting time,
however it is impossible to know in advance. OS knows the past burst times - make a prediction
using an average. It can be either nonpreemptive or preemptive scheduling.. It processes
shortest-remaining-time-first. The process interrupts running process if a new process enters the
queue. The new process must have shorter burst than remaining time.

Algorithm:
Step 1: Start the program.
Step 2: Get the input process and their burst time.
Step 3: Sort the processes based on burst time.
Step 4: Compute the waiting time and turnaround time for each process.
Step 5: Calculate the average waiting time and average turnaround
time. Step 6: Print the details about all the processes.
Step 7: Stop the program.

Program:
#include<stdio.h>
#include<conio.h>
voidmain()
{
int i,j,n,bt[30],at[30],st[30],ft[30],wat[30],wt[30],temp,temp1,tot,tt[30];
floatawt,att;
int p[15];
clrscr();
wat[1]=0;
printf("ENTER THE NO.OF PROCESS");
scanf("%d",&n);
printf("\nENTER THE PROCESS NUMBER,BURST TIME AND ARRIVAL TIME");
for(i=1;i<=n;i++)
{
scanf("%d\t %d\t %d",&p[i],&bt[i],&at[i]);
} printf("\nPROCESS\tBURSTTIME\
tARRIVALTIME");
for(i=1;i<=n;i++)
{
printf("\np%d\t%d\t\t%d",p[i],bt[i],at[i]);
}
for(i=1;i<=n;i++)

23
{
for(j=i+1;j<=n;j++)
{
if(bt[i]>bt[j])
{
temp=bt[i];
bt[i]=bt[j];
bt[j]=temp;
temp1=p[i];
p[i]=p[j];
p[j]=temp1;
}
}
if(i==1)
{ st[1]=
0;
ft[1]=bt[1];
wt[1]=0;
}
else
{
st[i]=ft[i-1];
ft[i]=st[i]+bt[i];
wt[i]=st[i];
}
}
printf("\n\n\t\t\tGANTT CHART\n");
printf("\n \n");
for(i=1;i<=n;i++)
printf("|\tp%d\t",p[i]);
printf("|\t\n");
printf("\n \n");
printf("\n");
for(i=1;i<=n;i++)
printf("%d \t\t",wt[i]);
printf("%d",wt[n]+bt[n]);
printf("\n \n");
for(i=2;i<=n;i++)
wat[i]=wt[i]-at[i];
for(i=1;i<=n;i++)
tt[i]=wat[i]+bt[i];
printf("\nPROCESS\tBURSTTIME\tARRIVALTIME\tWAITINGTIME\tTURNAROUNDTIM
E\n"); for(i=1;i<=n;i+
+)
{
printf("\np%d %5d %15d %15d %15d",p[i],bt[i],at[i],wat[i],tt[i]);

24
}
for(i=1,tot=0;i<=n;i++)
tot+=wt[i];
awt=(float)tot/n;
printf("\n\n\n AVERAGE WAITING TIME=%f",awt);
for(i=1,tot=0;i<=n;i++)
tot+=tt[i];
att=(float)tot/n;
printf("\n\n AVERAGE TURNAROUND TIME=%f",att);
getch();
}

Output:
enter the no.of process3
enter the process number,burst time and arrival time1 8 1
251
331
PROCESS BURSTTIME ARRIVALTIME
p1 8 1
p2 5 1
p3 3 1
GANTT CHART

| p3 | p2 | p1 |

0 3 8 16

PROCESS BURSTTIME ARRIVALTIME WAITINGTIME TURNAROUNDTIME


p3 3 1 0 2
p2 5 1 2 6
p1 8 1 7 14
AVERAGE WAITING TIME=3.666667
AVERAGE TURNAROUND TIME=7.333333

Result
The SJF scheduling algorithm has been implemented in C.

25
Ex No: 3C
IMPLEMENTATION OF FCFS SCHEDULING ALGORITHM

Aim
To write a C program to implement First Come First Serve scheduling algorithm.

Desription:
This is a non-preemptive technique.A single queue of ready processes is maintained, and the
dispatcher always picks the first one.This method does not emphasises throughput, since long
processes are allowed to monopoliseCPU.The response time with FCFS can be high (with respect
to execution time), especially if there is a high variance in process execution times.
This method penalises short processes following long ones, though no starvation is possible.
Jobs are processed in the order in which they arrive at a machine or work center

Algorithm:
Step 1: Start the program.
Step 2: Get the input process and their burst time.
Step 3: Sort the processes based on order in which it requests CPU.
Step 4: Compute the waiting time and turnaround time for each process.
Step 5: Calculate the average waiting time and average turnaround
time. Step 6: Print the details about all the processes.
Step 7: Stop the program.

Program:
#include<stdio.h>
#include<conio.h>
voidmain()
{
intbt[50],wt[80],at[80],wat[30],ft[80],tat[80];
inti,n;
floatawt,att,sum=0,sum1=0;
char p[10][5];
clrscr();
printf("\nenter the number of process ... ");
scanf("%d",&n);
printf("\nEnter the process name and burst-time:");
for(i=0;i<n;i++)
scanf("%s%d",p[i],&bt[i]);
printf("\nEnter the arrival-time:");
for(i=0;i<n;i++)
scanf("%d",&at[i]);
wt[0]=0;
for(i=1;i<=n;i++)

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

ft[0]=bt[0];
for(i=1;i<=n;i++)
ft[i]=ft[i-1]+bt[i];
printf("\n\n\t\t\tGANTT CHART\n");
printf("\n \n");
for(i=0;i<n;i++)
printf("|\t%s\t",p[i]);
printf("|\t\n");
printf("\n \n");
printf("\n");
for(i=0;i<n;i++)
printf("%d\t\t",wt[i]);
printf("%d",wt[n]+bt[n]);
printf("\n \n");
printf("\n");
for(i=0;i<n;i++)
wat[i]=wt[i]-at[i];
for(i=0;i<n;i++)
tat[i]=wat[i]+bt[i];
printf("\n FIRST COME FIRST SERVE\n");
printf("\n Process Burst-time Arrival-time Waiting-time Finish-time Turnaround-time\n"); for(i=0;i<n;i+
+)
printf("\n\n %d%s \t %d\t\t %d \t\t %d\t\t %d \t\t %d",i+1,p[i],bt[i],at[i],wat[i],ft[i],tat[i]);
for(i=0;i<n;i++)
sum=sum+wat[i];
awt=sum/n;
for(i=0;i<n;i++)
sum1=sum1+bt[i]+wt[i];
att=sum1/n;
printf("\n\nAverage waiting time:%f",awt);
printf("\n\nAverage turnaround time:%f",att);
getch();
}

Output:
enter the number of process ... 3
Enter the process name and burst-time:p1 2
p2 3
p3 4
Enter the arrival-time:0 1 2

27
GANTT CHART

| p1 | p2 | p3 |

0 2 5 9

FIRST COME FIRST SERVE


Process Burst-time Arrival-time Waiting-time Finish-time Turnaround-time
1p1 2 0 0 2 2
2p2 3 1 1 5 4
3p3 4 2 3 9 7
Average waiting time:1.333333
Average turnaround time:5.333333

Result:
The FCFS scheduling algorithm has been implemented in C.

28
Ex No: 3D
IMPLEMENTATION OF PRIORITY SCHEDULINGALGORITHM

Aim

To write a C program to implement Priority Scheduling algorithm.

Algorithm:
Step 1: Start the program.
Step 2: Get the input process and their burst time.
Step 3: Sort the processes based on priority.
Step 4: Compute the waiting time and turnaround time for each process.
Step 5: Calculate the average waiting time and average turnaround
time. Step 6: Print the details about all the processes.
Step 7: Stop the program.

Program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
voidmain()
{
intbt[30],pr[30],np;
intwt[30],tat[30],wat[30],at[30],ft[30];
inti,j,x,z,t;
float sum1=0,sum=0,awt,att;
char p[5][9],y[9];
clrscr();
printf("\nenter the number of process");

scanf("%d",&np);
printf("\nEnter the process,burst-time and priority:");
for(i=0;i<np;i++) scanf("%s%d
%d",p[i],&bt[i],&pr[i]);
printf("\nEnter the arrival-time:");
for(i=0;i<np;i++)
scanf("%d",&at[i]); for(i=0;i<np;i+
+) for(j=i+1;j<np;j++)
{
if(pr[i]>pr[j])
{
x=pr[j];
pr[j]=pr[i];
pr[i]=x;
strcpy(y,p[j]);
strcpy(p[j],p[i]);
strcpy(p[i],y);

29
z=bt[j];
bt[j]=bt[i];
bt[i]=z;

}
}
wt[0]=0;
for(i=1;i<=np;i++)
wt[i]=wt[i-1]+bt[i-1];
ft[0]=bt[0];
for(i=1;i<np;i++)
ft[i]=ft[i-1]+bt[i];
printf("\n\n\t\tGANTT CHART\n");
printf("\n \n");
for(i=0;i<np;i++)
printf("|\t%s\t",p[i]);
printf("|\t\n");
printf("\n \n");
printf("\n");
for(i=0;i<=np;i++)
printf("%d\t\t",wt[i]);
printf("\n \n");
printf("\n");
for(i=0;i<np;i++)
wat[i]=wt[i]-at[i];
for(i=0;i<np;i++)
tat[i]=wat[i]+bt[i];
printf("\nPRIORITY SCHEDULING:\n");

printf("\nProcess Priority Burst-time Arrival-time Waiting-time Turnaround-time");


for(i=0;i<np;i++) printf("\n\n%d%s\t%d\t\t%d\t\t%d\t%d\t\t
%d",i+1,p[i],pr[i],bt[i],at[i],wt[i],tat[i]); for(i=0;i<np;i++)
sum=sum+wat[i];
awt=sum/np;
for(i=0;i<np;i++)
sum1=sum1+tat[i];
att=sum1/np;
printf("\n\nAverage waiting time:%f",awt);
printf("\n\nAverageturn around time is:%f",att);
getch();
}

Output:

30
Enter the number of process3
Enter the process, burst-time and priority:
p1 3 3
p2 4 2
p3 5 1
Enter the arrival-time: 0 1 2

GANTT CHART

| p3 | p2 | p1 |

0 5 9 12

PRIORITY SCHEDULING:
Process Priority Burst-time Arrival-time Waiting-time Turnaround-time

1p3 1 5 0 0 0

2p2 2 4 1 5 3

3p1 3 3 2 9 5

Average waiting time: 3.666667


Average turnaround time is: 2.666667

Result
The Priority scheduling algorithm has been implemented in C.

31
Ex No: 4
PRODUCER CONSUMER PROBLEM USING SEMAPHORES

Aim:
To write a C program to implement producer consumer problem using semaphore

Algorithm:
Step 1: Declarethe buffer size variable.
Step 2: Initialize empty, full and the value of mutex.
Step 3: For case 1 , produce the item till the buffer is full after performing the wait
operation of variables empty and mutex.
Step 4: Then perform signal of full.
Step 5: For case 2, consume the item till the buffer is empty. Perform the wait and signal operation..
Step 6: print the contents of the buffer.

Program:
#include<stdio.h>
#include<string.h>
#define SIZE 3
struct process
{
char a[10];
}buffer[SIZE];
intmutex=1,full=0,empty=SIZE,f=0;
int main()
{
//intmutex=1,full=0,empty=SIZE,f=0;
intch,i;
printf("\tProdecer Consumer Problem:\n");
while(1)
{
printf("\n The choices are\n");
printf("1.Producer Routine\n2.Consumer Routine\n3.Buffer Contents\n4.Exit\n");

printf("Enter your
Choice:"); scanf("%d",&ch);
switch(ch)
{
case 1:
empty=wait(empty);
mutex=wait(mutex);
if(f==0)
{
printf("\nEnter the item to be added:\n");
scanf("%s",&buffer[full]);
full=signal(full);
printf("\nItem Produced Successfully:\n");
}
else
{
printf("\nBuffer is full\n");
32
f=0;
}
mutex=signal(mutex);
break;
case 2:
full=wait(full);
mutex=wait(mutex);
if(f==0)
{
printf("\nOne Item is Consumed:\n"); printf("\
nConsumed item is: %s\n",buffer[0].a);
for(i=0;i<SIZE;i++)
strcpy(buffer[i].a,buffer[i+1].a);
empty=signal(empty);
}
else
{
printf("\nBuffer is empty\n");
f=0;
}
mutex=signal(mutex);
break;
case 3:
if(full!=0)
{
for(i=0;i<full;i++) printf("\n%s\
n",buffer[i].a);
}
else
printf("\nBuffer is empty\n");
break;
case 4:
exit(0);
default:

printf("Enter Correct
Option"); break;
}
}
}
int wait(int s)
{
if(s==0)
f=1;
else
s--;
return s;
}
int signal(int s)
{ s+
+;
return s;
}

33
Output:
The choices are
1. Producer Routine
2. Consumer Routine
3. Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
1
Item Produced Successfully:
The choices are
1. Producer Routine
2. Consumer Routine
3. Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
2
Item Produced Successfully:
The choices are
1. Producer Routine
2. Consumer Routine
3. Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:3
Item Produced
Successfully: The choices
are
1. Producer Routine
2. Consumer Routine

3. Buffer Contents
4.Exit
Enter your Choice:1
Buffer is full
The choices are
1. Producer Routine
2. Consumer Routine
3. Buffer Contents
4.Exit
Enter your Choice:2
One Item is Consumed:
Consumed item is: 1

34
The choices are
1. Producer Routine
2. Consumer Routine
3. Buffer Contents
4.Exit

Enter your Choice:

Result
Thus the producer consumer problem using semaphores has been implemented in C.

35
Ex No: 5 Implementation of Shared Memory

Aim
To demonstrate communication between process using shared memory.

Algorithm
Server
1. Initialize size of shared memory shmsize to 27.
2. Initialize key to 2013 (some random value).
3. Create a shared memory segment using shmget with key & IPC_CREAT as parameter.
a. If shared memory identifier shmid is -1, then stop.
4. Display shmid.
5. Attach server process to the shared memory using shmmat with shmid as parameter.
a. If pointer to the shared memory is not obtained, then stop.
6. Clear contents of the shared region using memset function.
7. Write a–z onto the shared memory.
8. Wait till client reads the shared memory contents
9. Detatch process from the shared memory using shmdt system call.
10. Remove shared memory from the system using shmctl with IPC_RMID argument
11. Stop

Client
1. Initialize size of shared memory shmsize to 27.
2. Initialize key to 2013 (same value as in server).
3. Obtain access to the same shared memory segment using same key.
a. If obtained then display the shmid else print "Server not started"
4. Attach client process to the shared memory using shmmat with shmid as parameter.
a. If pointer to the shared memory is not obtained, then stop.
5. Read contents of shared memory and print it.
6. After reading, modify the first character of shared memory to '*'
7. Stop

36
Program

Server
/* Shared memory server - shms.c */
#include <stdio.h>
#include <stdlib.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27

main()
{
char c; int
shmid;
key_t key = 2013; char *shm,
*s;
if ((shmid = shmget(key, shmsize, IPC_CREAT|0666)) < 0)
{
perror("shmget"); exit(1);
}
printf("Shared memory id : %d\n", shmid);
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat"); exit(1);
}
memset(shm, 0, shmsize); s =
shm;
printf("Writing (a-z) onto shared memory\n"); for (c = 'a'; c <=
'z'; c++)
*s++ = c;
*s = '\0';
while (*shm != '*');
printf("Client finished reading\n"); if(shmdt(shm) != 0)
fprintf(stderr, "Could not close memory segment.\n");
shmctl(shmid, IPC_RMID, 0);
}

37
Client

/* Shared memory client - shmc.c */


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27

main()
{
int shmid;
key_t key = 2013; char
*shm, *s;
if ((shmid = shmget(key, shmsize, 0666)) < 0)
{
printf("Server not started\n"); exit(1);
}
else
printf("Accessing shared memory id : %d\n",shmid); if ((shm = shmat(shmid,
NULL, 0)) == (char *) -1)
{
perror("shmat"); exit(1);
}
printf("Shared memory contents:\n"); for (s = shm;
*s != '\0'; s++)
putchar(*s); putchar('\n');
*shm = '*';
}

38
Output

Server
$ gcc shms.c -o shms

$ ./shms
Shared memory id : 196611 Writing (a-z) onto
shared memory Client finished reading

Client
$ gcc shmc.c -o shmc

$ ./shmc
Accessing shared memory id : 196611 Shared
memory contents: abcdefghijklmnopqrstuvwxyz

Result
Thus contents written onto shared memory by the server process is read by the client
process.

39
Ex.No:6(a) BANKERS ALGORITHM FOR DEADLOCK AVOIDANCE

Aim:
To write a program to implement bankers algorithm for deadlock avoidance.

Algorithm:

1. Start the program.


2. Get the number of process, resource, allocation matrix, Maximum matrix and available matix.
3. Calcualte need matrix using Maximum matrix and allocation matrix i.e.,
NEED[i,j]=MAX[i,j]-ALLOC[i,j]. Also initialize work matrix i.e., WORK[j]=AVAIL[j].

4. Now find safety sequence of the system using work matrix,need matrix.
5. Now compare NEED and WORK matrix, if NEED[i,j]<=WORK[j] then
Execute the corresponding process also calculate new work matrix i.e.,

WORK[j] =WORK[j]+ALLOC[i,j].

6. If condition doesn’t satisfy, move to next process and repeat Step 5, until completion of
all processes and print the safety sequence.
7. If any process request for resource, get the process id and request matrix from the user.
8. Check the following conditions for the respective process using Request
matrix,Need matrix and Available matrix i.e., REQ[j]<=NEED[k,j] and

REQ[j]<=AVAIL[j].

9. If the above condition satisfies, request can be granted and proceed next stepotherwise
display error as “Request cannot be granted”.
10. Now calculate new Available matrix,Allocation matrix,Need matrix
and Work matrix i.e.,AVAIL[j]=AVAIL[j]-REQ[j],

WORK[j]=AVAIL[j],ALLOC[k,j]=ALLOC[k,j]+REQ[j],

NEED[k,j]=NEED[k,j]-REQ[j].

11. To find safety sequence of the system, repeat Step 5 and Step 6 for all processes.
12. Then print the safety sequence of execution of processes.
13. Stop the program.

40
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h> void
main()
{
int alloc[20][20],max[20][20],avail[20],need[20][20],work[20]={0}; int
newavail[20],req[20]={0},check=0,check2=0,cond,p;
int i=0,j=0,m=0,n=0,x=0,c[20]={0},count,count2,a[20],b; int x2=0,c2[20];
clrscr();
printf("Enter the no. of resources\n"); scanf("%d",&m);
printf("Enter the no. of process"); scanf("%d",&n);
printf("\n Enter the resources for available\n"); for(j=1;j<=m;j++)
{
printf("Enter the %d resources of avail",j); scanf("%d", &avail[j]);
work[j]=avail[j];
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
printf("Enter the %d resources of %d alloc",j,i); scanf("%d", &alloc[i][j]);
}
for(j=1;j<=m;j++)
{
printf("\n Enter the %d resource of %d max",j,i); scanf("%d",&max[i][j]);
need[i][j]=max[i][j]-alloc[i][j];
}
}
printf("\n Allocation max need\n");
for(i=1;i<=n;i++)
{

for(j=1;j<=m;j++) printf("%2d",alloc[i]
[j]); printf("\t"); for(j=1;j<=m;j++)
printf("%2d",max[i][j]); printf("\
t"); for(j=1;j<=m;j++)

printf("%2d",need[i][j]); printf("\n");
}

printf("\n Process executes in this order\n"); do{


for(i=1;i<=n;i++)
{
count=0; if(c[i]!=i+1)
{
for(j=1;j<=m;j++)
{
if(need[i][j]<=work[j]) count =
count+1;
}
if(count == m)

41
{
printf("p%d\t",i); c[i]=i+1;
x = x+1; for(j=1;j<=n;j++)
work[j]=work[j]+alloc[i][j];
}
}
}
check = check +1;
}
while(x<n && check <=n); if(x==n)
printf("\n system is in saftey\n"); else
printf("\n System is not in saftey");
printf("\n Checking the bankers algorithm after the request"); printf("\n Enter the
request process number"); scanf("%d",&p);
printf("\n Enter the values");
for(j=1;j<=m;j++)
{
scanf("%d",&req[j]);
}
for(j=1;j<=m;j++)
{
if(req[j]<=avail[j]&& req[j]<=need[p][j])
cond=cond+1;
}
if(cond != m)
{
for(j=1;j<=m;j++)
{
alloc[p][j]=alloc[p][j]+req[j];
avail[j]=avail[j]-req[j]; need[p]
[j]=need[p][j]-req[j];
}
}
else
{
printf("req is not satisfied"); exit(0);
}
printf("\n Execution of process after request");
do
{
for(i=1;i<=n;i++)
{
count2=0; if(c2[i]!=i+1)
{
for(j=1;j<=m;j++)
{
if(need[i][j]<=avail[j]) count2 =
count2+1;
}
if(count2 == m)
{
printf("p%d\t",i); c2[i]=i+1;
x2 = x2+1;

42
for(j=1;j<=n;j++) avail[j]=avail[j]+alloc[i][j];
}
}
}
check2 = check2 +1;
}
while(x2<n && check2 <=n); if(x2==n)
printf("\n system is in saftey\n"); else
printf("\n System is not in saftey"); getch();
}

Output

Enter the no. of resources 3


Enter the no. of process3
Enter the resources for available
Enter the 1 resources of avail1
Enter the 2 resources of avail2
Enter the 3 resources of Avail3
Enter the 1 resources of 1 alloc3
Enter the 2 resources of 1 alloc2
Enter the 3 resources of 1 alloc1
Enter the 1 resource of 1 max1
Enter the 2 resource of 1 max2
Enter the 3 resource of 1 max3
Enter the 1 resources of 2 alloc2
Enter the 2 resources of 2 alloc2
Enter the 3 resources of 2 alloc2
Enter the 1 resource of 2 max3
Enter the 2 resource of 2 max3
Enter the 3 resource of 2 max3
Enter the 1 resources of 3 alloc2
Enter the 2 resources of 3 alloc2
Enter the 3 resources of 3 alloc2
Enter the 1 resource of 3 max1
Enter the 2 resource of 3 max2
Enter the 3 resource of 3 max3
Allocation max need

43
321 -2 10 2

222 3

222 1

Process executes in this order

p1 p2 p3
system is in saftey
Checking the bankers algorithm after the request Enter
the request process number2
Enter the values1
1
1
execution after the request p1
p2 p3
the system is in safe state.

Result:
The program for banker’s algorithm for deadlock avoidance was implemented and hence verified.

44
Ex No: 6(b) IMPLEMENTATION OF DEADLOCK DETECTION

Aim:
To write a program to implement Deadlock detection algorithm.

Algorithm:
Step 1: Start the program.
Step 2: Get the values of resources and processes.

Step 3: Get the allocation and request matrix value.

Step 4: Get the available instances for each resources


Step 5: Check whether its possible to allocate using below condition.
Step 6: If Need<=Work update work as work=work +allocation
Step 7: Else proceed with next process.
Step 8: If it is possible to allocate then the system is in safe state.
Step 9: Else system is not in safe state.
Step 10: Stop the program.

Program:
#include <stdio.h>
main()
{
int found,flag,l,p[5][6],tp,tr,c[5][6],i,j,k=1,m[6],r[6],a[6],temp[6],sum=0;
printf("Enter total no of processes");
scanf("%d",&tp);
printf("Enter total no of resources");
scanf("%d",&tr);
printf("Enter claim (Max. Need) matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&c[i][j]);
}
printf("Enter allocation matrix\n");
for(i=1;i<=tp;i++)

45
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&p[i][j]);
}
printf("Enter resource vector (Total resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&r[i]);
}
printf("Enter availability vector (available resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=1;i<=tp;i++)
{
sum=0;
for(j=1;j<=tr;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=tp;i++)
{
for(l=1;l<k;l++) if(i!
=m[l])
{

46
flag=1;
for(j=1;j<=tr;j++)
if(c[i][j]<temp[j])
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=tr;j++) temp[j]
+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0) printf("%d\
t",j);
}
}

47
Output :
Enter total no. of processes 4
Enter total no. of resources 5
Enter claim (Max. Need) matrix :0 1 0 0 1
00101
00001
10101
Enter allocation matrix :1 0 1 1 0
11000
00010
00000
Enter resource vector (Total resources) :
21121
Enter availability vector (available resources) :
00001
deadlock causing processes are : 2 3

Result:
The program for deadlock detection algorithm was implemented and hence verified

48
Ex.No: 7. IMPLEMENTATION OF MEMORY MANAGEMENT SCHEME

Aim

To write a program to implement memory management scheme.

A. First fit Algorithm

Algorithm
1. Start the process
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the first hole that is big enough searching
5. Start at the beginning of the set of holes
6. If not start at the hole that is sharing the pervious first fit search end
7. Compare the hole
8. if large enough then stop searching in the procedure
9. Display the values
10. Stop the process

Program
#include<stdio.h>void main()
{
int i,j,temp,f[10],fp[10];
int no,p[15],part[15],pno,pr[15],prmem[15];
printf("\n*************");
printf("\n Implementation of first-fit algorithm"); printf("\
n******************");
printf("\n Enter the number of partitions:");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
p[i]=i;
printf("\n Enter the memory size for partition:%d:\t",i);
scanf("%d",&part[i]);

49
}
printf("\n Enter the number of process:");
scanf("%d",&pno);
for(i=1;i<=pno;i++)
{
pr[i]=i;
printf("\n Enter the size for process %d: \t",i);
scanf("%d",&prmem[i]);
}
printf("\n ----------\n");
printf("process|\t Partition|\t Free_memory|\n");
printf("\n ------------- \n");
j=1;
for(i=1;i<=no;i++)
{

f[i]=0;
fp[i]=0;
}
while(j<=pno)
{
for(i=1;i<=no;i++)
{
if((part[i]>=prmem[j])&&(f[i]==0))
{
part[i]=part[i]-prmem[j];
fp[j]=1;
f[i]=1;
printf("%d\t\t%d\t\t%d\n",pr[j],p[i],part[i]);
goto l1;
}
}
l1:
j++;
}
for(i=1;i<=no;i++)

50
{
if(f[i]==0)
{
printf ("%d\t\t %d \t\t \n",p[i],part[i]);
}
}
printf("\n The following process is not allocated:"); for(i=1;i<=pno;i+
+)
{
if(fp[i]==0)
{
printf("%d",pr[i]);
}
}

51
Output

******************
Implementation of first-fit algorithm
******************
Enter the number of partitions:3
Enter the memory size for partition:1: 60
Enter the memory size for partition:2: 80
Enter the memory size for partition:3: 100
Enter the number of process:3
Enter the size for process 1: 55
Enter the size for process 2: 75
Enter the size for process 3: 90

process| Partition| Free_memory|

1 1 5
2 2 5
3 3 10
The following process is not allocated:0

Result
The program for first fit was implemented and hence verified

52
B. Best Fit Algorithm

Algorithm
1. Start the process
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the best hole that is small enough searching
5. Start at the best of the set of holes
6. If not start at the hole that is sharing the pervious best fit search end

7. Compare the hole


8. If small enough then stop searching in the procedure
9. Display the values
10. Stop the process

Program

#include<stdio.h>
main()
{
int i,j,temp,f[10],fp[10];
int no,p[15],part[15],pno,pr[15],prmem[15];
printf("\n***********************"); printf("\
n implementation of best-fit algorithm");
printf("\n**************************");
printf("\n Enter the number of partitions:");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
p[i]=i;
printf("\n Enter the memory size for partition %d:\t",i);
scanf("%d",&part[i]);
}
for(i=1;i<=no;i++)
{
for(j=1;j<=i;j++)
{

53
if(part[j]>part[i])
{
temp=part[i];
part[i]=part[j];
part[j]=temp;
temp=p[i];
p[i]=p[j];
p[j]=temp;

}
}
}
printf("\n Enter the number of process:");
scanf("%d",&pno);
for(i=1;i<=pno;i++)
{
pr[i]=i;
printf("\n Enter the size for process %d:\t",i);
scanf("%d",&prmem[i]);
}
printf("\n -------------- \n");
printf("PROCESS|\t PARTITION|\t FREE_MEMORY|\n");
printf("\n -----------\n");
j=1;
for(i=1;i<=no;i++)
{ f[i]=
0;
fp[j]=0;
}
while(j<=pno)
{
for(i=1;i<=no;i++)
{
if((part[i]>=prmem[j])&&(f[i]==0))
{

54
part[i]=part[i]-prmem[j];
fp[j]=1;
f[i]=1;
printf("%d \t\t %d \t\t %d \n",pr[j],p[i],part[i]);
goto l1;
}
}
l1:

j++;
}
for(i=1;i<=no;i++)
{
if(f[i]==0)
{
printf("%d \t\t %d \t\t \n",p[i],part[i]);
}
}
printf("\n The following process is not allocated:"); for(i=1;i<=pno;i+
+)
{
if(fp[i]==0)
{
printf("%d",pr[i]);
}
}
}

55
Output

***********************
implementation of best-fit algorithm
**************************
Enter the number of partitions:3
Enter the memory size for partition 1: 2
Enter the memory size for partition 2: 6
Enter the memory size for partition 3: 9
Enter the number of process:4
Enter the size for process 1: 2
Enter the size for process 2: 3
Enter the size for process 3: 3
Enter the size for process 4: 6

PROCESS| PARTITION| FREE_MEMORY|

1 1 0
2 2 3
3 3 6
The following process is not allocated:4

Result
The program for best fit was implemented and hence verified

56
C. Worst Fit Algorithm

Algorithm
1. Start the process
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the best hole that is small enough searching
5. Start at the best of the set of holes
6. If not start at the hole that is sharing the pervious best fit search end
7. Compare the hole
8. If small enough then stop searching in the procedure
9. Display the values
10. Stop the process

Program

#include<stdio.h>
main()
{
int i,j,temp,f[10],fp[10];
int no,p[15],prmem[15],part[15],pr[15],pno;
printf("\n*******************\n");
printf("enter no of partitions:\n");
scanf("%d",&no);
for(i=1;i<=no;i++)

{
p[i]=i;
printf("enter the memory for partition %d\t",i);
scanf("%d",&part[i]);
}
for(i=1;i<=no;i++)
{
for(j=1;j<=i;j++)
{
if(part[j]<part[i])
{

57
temp=part[i];
part[i]=part[j];
part[j]=temp;
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
printf("\n free memory");
for(i=1;i<=no;i++)
{
printf("\n partition %d:\t %d",p[i],part[i]);
}
printf("\n enter the number of process:");
scanf("%d",&pno);
for(i=1;i<=pno;i++)
{
pr[i]=i;
printf("\n enter the size of process %d:\t",i);
scanf("%d",&prmem[i]);
}
printf("\n ------------- \n");

printf("process| \t partition \t free memory|\n");


printf("\n --------------- \n");
j=1;
for(i=1;i<=no;i++)
{ f[i]=
0;
fp[j]=0;
}
while(j<=pno)
{
for(i=1;i<=no;i++)
{ if((part[i]>=prmem[j])&&(f[i]==0))

58
{
part[i]=part[i]-prmem[j];
fp[j]=1;
f[i]=1;
printf("%d \t %d \t %d \n",pr[j],p[j],part[i]);
goto l1;
}
}
l1:
j++;
}for(i=1;i<=no;i++)
{
if(f[i]==0)
{
printf("\t %d \t %d \n",p[i],part[i]);
}
}
printf("\n the following process is not allocated:");
for(i=1;i<=pno;i++)
{
if(fp[i]==0)
{

printf("%d",pr[i]);
}
}
}
Output
enter no of partitions:
3
enter the memory for partition 1 20
enter the memory for partition 2 30
enter the memory for partition 3 10
free memory
partition 2: 30

59
partition 1: 20
partition 3: 10
enter the number of process:3
enter the size of process 1: 12
enter the size of process 2: 22
enter the size of process 3: 7

process| partition free memory|

1 2 18
3 3 13
3 10

the following process is not allocated:2

Result
The program for worst fit was implemented and hence verified.

60
PAGE REPLACEMENT ALGORITHMS

Ex. No 8A: IMPLEMENTATION OF FIFO ALGORITHM

Aim:
To implement First in First Out page replacement technique.

Algorithm:
Step 1: Start the process
Step 2: Declare the size with respect to page length
Step 3: Check the need of replacement from the page to memory
Step 4: Check the need of replacement from old page to new page in memory
Step 5: Forma queue to hold all pages
Step 6: Insert the page require memory into the queue
Step 7: Check for bad replacement and page fault
Step 8: Get the number of processes to be inserted
Step 9: Display the values
Step 10: Stop the process

Program:
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0; printf("\
n ENTER THE NUMBER OF PAGES:\n");

scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");

61
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;
}

62
Output
ENTER THE NUMBER OF PAGES: 20
ENTER THE PAGE NUMBER : 70120304230321201701
ENTER THE NUMBER OF FRAMES :3

ref string page frames


7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1
Page Fault Is 15

Result:
The program for First in First Out page replacement technique was implemented and hence
verified.

63
Ex No: 8B IMPLEMENTATION OF LRU ALGORITHM

Aim:
To implement Least Recently Used page replacement technique.

Algorithm:
Step 1: Start the process
Step 2: Declare the size
Step 3: Get the number of pages to be inserted
Step 4: Get the value
Step 5: Declare counter and stack
Step 6: Select the least recently used page by counter value
Step 7: Stack them according the selection.
Step 8: Display the values
Step 9: Stop the process

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("Enter the reference
string:"); for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter 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;

64
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;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)

65
{
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);
}
Output:
Enter no of pages:10
Enter the reference string:7 5 9 4 3 7 9
6 2 1 Enter no of frames:3
7
5
5 9
5 9
3 9
3 7
3 7
6 7
6 2
6 2
The no of page faults is 10

Result:

The program for Least Recently Used page replacement technique was implemented and
hence verified .

66
Ex No: 8C IMPLEMENTATION OF LFU ALGORITHM

Aim:
To implement Least Frequently Used page replacement technique.

Algorithm:
Step 1: Start the process
Step 2: Declare the size
Step 3: Get the number of pages to be inserted
Step 4: Get the value
Step 5: Declare counter and stack
Step 6: Select the least frequently used page by counter value
Step 7: Stack them according the selection.
Step 8: Display the values
Step 9: Stop the process

Program:
#include<stdio.
h> int main()
{
int f,p;
int
pages[50],frame[10],hit=0,count[50],time[50]
; int i,j,page,flag,least,minTime,temp;
printf("Enter no of frames : ");
scanf("%d",&f);
printf("Enter no of pages : ");
scanf("%d",&p);

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

frame[i]=-1;
}
for(i=0;i<50;i++)
{
count[i]=0;
}
printf("Enter page no : \n");

67
for(i=0;i<p;i++)
{
scanf("%d",&pages[i]);
}
printf("\n");
for(i=0;i<p;i++)
{
count[pages[i]]
++;
time[pages[i]]=
i; flag=1;
least=frame[0];
for(j=0;j<f;j++)
{
if(frame[j]==-1 || frame[j]==pages[i])
{
if(frame[j]!=-1)
{
hit++;
}
flag=0;
frame[j]=pages[
i]; break;
}
if(count[least]>count[frame[j]])
{
least=frame[j];
}

}
if(flag)
{
minTime=50;
for(j=0;j<f;j++)
{
if(count[frame[j]]==count[least] && time[frame[j]]<minTime)
{
temp=j;

68
minTime=time[frame[j]];
}
}
count[frame[temp]]=0;
frame[temp]=pages[i];
}
for(j=0;j<f;j++)
{
printf("%d ",frame[j]);
}
printf("\n");
}
printf("Page hit =
%d",hit); return 0;
}

69
Output
Enter no of
frames: 3 Enter
no of pages:10
Enter page no:
2
3
4
2
1
3
7
5
4
3

2 -1 -1
2 3 -1
2 3 4
2 3 4
2 1 4
2 1 3
2 7 3
2 7 5
2 4 5
2 4 3
Page hit=1

Result:

The program for Least Frequently Used page replacement technique was implemented and hence
Verified.

70

You might also like