0% found this document useful (0 votes)
13 views90 pages

Os Lab Manual

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)
13 views90 pages

Os Lab Manual

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/ 90

EX.

NO: 1 BASICS OF UNIX COMMANDS


DATE:

AIM
To study various UNIX command in detail.

COMMANDS
GENERAL COMMANDS
NAME SYNTAX DESCRIPTION EXAMPLE
Who $who Displays users who [it40@syamantaka ~]$ who
are currently root pts/0 2011-03-10 20:57 (10.2.1.73)
logged on it40 pts/4 2011-03-10 23:17 (10.2.1.204)
Who am i $who am i Displays our own [it40@syamantaka ~]$ who am i
login terminal and it40 pts/4 2011-03-10 23:17 (10.2.1.204)
other details
finger $ finger it3 Displays system [it3@syamantaka ~]$ finger it3
[user] biography on user Login: it3 Name: (null)
`[user]'. Directory: /home/it3 Shell: /bin/bash
On since Tue Mar 15 02:30 (IST) on pts/0 from
10.2.1.204
No mail.
No Plan.
Date $date Displays the date [it40@syamantaka ~]$ date
which is stored in Thu Mar 10 23:19:17 IST 2011
particular format
Calendar $cal<month><year> Displays calendar [it40@syamantaka ~]$ cal 1 1983
of specified month January 1983
and year Su Mo Tu We Th Fr Sa
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 31
Clear $clear Clears the screen [it40@syamantaka ~]$ clear
and displays the [it40@syamantaka ~]$
new screen
Uname $uname Displays the OS [it40@syamantaka ~]$ uname
which is used. Linux
#1 SMP Fri Jan 26 14:42:21 EST 2007 i686
i6 86 i386 GNU/Linux
$uname –a Displays all [it40@syamantaka ~]$ uname -a
machine details Linux syamantaka.vec 2.6.18-8.el5xen
$uname –s Displays the OS [it40@syamantaka ~]$ uname -s

1
name Linux
$uname –v Displays the [it40@syamantaka ~]$ uname -v
version of OS #1 SMP Fri Jan 26 14:42:21 EST 2007
$uname –r Displays the release
[it40@syamantaka ~]$ uname -r
of OS 2.6.18-8.el5xen
$uname –n Displays the name
[it40@syamantaka ~]$ uname -n
of network mode syamantaka.vec
$uname –m Displays the type
[it40@syamantaka ~]$ uname -m
of OS i686
Binary $bc Used for [it40@syamantaka ~]$ bc
calculator calculation 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'.
15 + 2
17
Identifier $id Displays userid and [it40@syamantaka ~]$ id
groupid uid=575(it40) gid=575(it40) groups=575(it40)
context=user_u:system_r:unconfined_t
Present $pwd Displays the [it40@syamantaka ~]$ pwd
working currently working /home/it40
Directory directory
Echo $echo<text> Displays the text [it40@syamantaka ~]$ echo os
given by the user os
Man $man <command> Displays the details $man clear
of specified clear(1)
command clear(1)
NAME
clear - clear the terminal screen
SYNOPSIS
clear
DESCRIPTION
clear clears your screen if this is possible. It looks
in the environment for the terminal type and then
in the terminfo database to figure out how to clear
the screen.
clear ignores any command-line parameters that
may be present.
Touch $touch <filename> Creates a file [it40@syamantaka ~]$ touch f1
Tty $tty Displays the [it40@syamantaka ~]$ tty
terminal number of /dev/pts/4
system

2
LISTING OPTIONS

SYNTAX DESCRIPTION EXAMPLE


$ls Lists all files in the present working [it40@syamantaka ~]$ ls
directory a.out fact.c ffs.c hi max.c one.sh rad1.c
rr.c sjf. su two.c
$ls –a Displays all hidden files of the user [it40@syamantaka ~]$ ls -a
. .bash_logout fact ffs.c lg.c one.c
rad .ragr.c.swp six.c ss two.c
a.out .bashrc fc.c four.c max.c
.one.sh.swp rad.c .sf.c.swp sjf.c sum.c
.viminfo
$ls –c Lists all subdirectories of the file in [it40@syamantaka ~]$ ls -c
columnwise fashion f1 ss fcfs.c nandy.sh lg.c five.c three.c
fc.c
sjf. a.out sjf.c mat.c six.c rad two.c fact.c
$ls –d Displays the root directory of the [it40@syamantaka ~]$ ls -d
present directory .
$ls –r Reverses the order in which files and [it40@syamantaka ~]$ ls -r
sundirectories are displayed two.sh sum.c sjf.c shivani rad.c priority.c nandy.sh
lg.c five.c fc.c f1

$ls –R Lists the files and subdirectories in [it40@syamantaka ~]$ ls -R


hierarchial order .:
a.out fact.c ffs.c hi max.c one.sh rad1.c
rr.c sjf. su two.c
f1 fc.c five.c lg.c nandy.sh priority.c rad.c
shivani sjf.c sum.c two.sh
$ls –t Displays the files in the order of [it40@syamantaka ~]$ ls -t
modification f1 ss fcfs.c nandy.sh lg.c five.c three.c fc.c
$ls –p Displays files and sundirectories by a [it40@syamantaka ~]$ ls -p
slashmark a.out fact.c ffs.c hi/ max.c one.sh rad1.c
rr.c sjf. su two.c
$ls –i Displays the node number of each [it40@syamantaka ~]$ ls -i
file 26543903 a.out 26545681 ffs.c 26545241 max.c
26544524 rad1.c 26546141 sjf. 26544865 two.c
$ls –l Lists the permission given to each [it40@syamantaka ~]$ ls -l
file total 248
-rwxrwxr-x 1 it40 it40 6356 Feb 24 21:34 a.out
-rw-rw-r-- 1 it40 it40 0 Mar 10 23:31 f1
-rw-rw-r-- 1 it40 it40 193 Jan 6 21:58 fact

3
PATTERN SEARCHING COMMAND

NAME SYNTAX DESCRIPTION EXAMPLE


Grep $grep<pattern> Displays the line in which the [it3@syamantaka ~]$ grep
<filename> given pattern is seen include io.c
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>

FILE MANIPULATION COMMANDS

NAME SYNTAX DESCRIPTION EXAMPLE


Cat>> $cat>><filename> Edit contents of existing file [it3@syamantaka ~]$
cat>>os
os is an interface
Cat $cat <filename> View the contents of the file [it3@syamantaka ~]$ cat os
os is an interface
Cat $cat –n filename Displays the file with line [it3@syamantaka ~]$ cat -n
numbers os
os is an interface
More $more <filename> Displays the file page by page [it3@syamantaka ~]$ more os
os is an interface
More+ $more+10 <filename> Files will be displayed from the [it3@syamantaka ~]$ more
10th page onwards +10 fibo.sh
a=$b
b=$c
i=`expr $i + 1`
echo $c
done
Wc $wc Counts the number of [it3@syamantaka ~]$ wc os
words,characters and lines for a 2 4 20 os
given file
Wc –l $wc –l Displays the number of lines [it3@syamantaka ~]$ wc -l os
2 os
Wc –w $wc –w Displays the number of words [it3@syamantaka ~]$ wc -w
os
4 os
Wc –c $wc –c Displays only the number of [it3@syamantaka ~]$ wc -c os
characters 20 os
Cp $cp Copy a file [it3@syamantaka ~]$ cp os so
<filename1><filename [it3@syamantaka ~]$ cat so

4
2> os is an interface
Mv $mv<filename1><filen Move a file from a directory to [it3@syamantaka ~]$ mv os
ame2> another directory op
[it3@syamantaka ~]$ cat op
os is an interface
rm rm <filename> removes a file [it3@syamantaka ~]$ rm f1
rm –i filename ask you for confirmation before [it3@syamantaka ~]$ rm -i f2
actually deleting anything rm: remove regular file `f2'? y
diff <filename1> compares files, and shows where [it3@syamantaka ~]$
Diff <filename2 > they differ cat>>check1
anand
paul
rajesh
[it3@syamantaka ~]$
cat>>check2
anand
rajesh
[it3@syamantaka ~]$ diff
check1 check2
2d1
< paul
Ln –s $ln –s <source Creates a soft link between files. [it3@syamantaka ~]$ cat>>os
filename><new Here contents are copied to a new os is resident monitor
filename> file but the memory addresses of [it3@syamantaka ~]$ ln -s os
both files are same.[After creating os1
the link (i.e.,) naming a file with 2 [it3@syamantaka ~]$ cat os
different names,if the original file os is resident monitor
is deleted ,the newly created file is [it3@syamantaka ~]$ cat os1
automatically deleted] os is resident monitor
[it3@syamantaka ~]$ rm os
[it3@syamantaka ~]$ cat os1
cat: os1: No such file or
directory
[it3@syamantaka ~]$
Ln $ln <source Creates a hard link between files [it3@syamantaka ~]$ cat>>os
filename><new .Here contents is copied to a new os is an interface
filename> file which is saved in a new [it3@syamantaka ~]$ ln os os1
address. .[After creating the link [it3@syamantaka ~]$ cat os
(i.e.,) naming a file with 2 os is an interface
different names, if the original file [it3@syamantaka ~]$ cat os1
is deleted ,the newly created file is os is an interface
not deleted] [it3@syamantaka ~]$ rm os
[it3@syamantaka ~]$ cat os1
os is an interface

5
FILTER COMANDS

NAME SYNTAX DESCRIPTION EXAMPLE


Head $head <filename Displays the top 10 lines of the [it3@syamantaka ~]$
file head alpha
a
b
c
d
e
f
g
h
i
j
Head - $head -5 <filename> Displays the top 5 lines of the file [it3@syamantaka ~]$
5 head -5 alpha
a
b
c
d
e
Tail $tail <filename> Displays the last 10 lines of the [it3@syamantaka ~]$ tail
file alpha
q
r
s
t
u
v
w
x
y
z
Tail –t $tail -5 <filename Displays the last 5 lines of the file [it3@syamantaka ~]$ tail
-5 alpha
v
w
x
y
z
Paste $paste Paste two files in vertical manner [it3@syamantaka ~]$
<filename1><filename2> paste f1 f2
hi hello hi haii

6
Sort $sort <filename> Sorts the contents of the file in [it3@syamantaka ~]$
alphabetical order sort alpha
a
b
c
d
e
f
g
h
ij
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

Sort –r $sort –r<filename> Sorts the contents of the file in [it3@syamantaka ~]$
reversed alphabetical order sort -r alpha
z
y
x
w
v
u
t
s
r
q
p
o
n
m
l
k

7
j
i
h
g
f
e
d
c
b
a

DIRECTORY COMMANDS

NAME SYNTAX DESCRIPTION EXAMPLE


Present working $pwd Displays the currently working [it40@syamantaka
Directory directory ~]$ pwd
/home/it40
Make directory $ mkdir subdir mkdir creates a new [it3@syamantaka ~]$
subdirectory inside of the mkdir book
directory where you are
currently working
Change directory $ cd Misc cd moves you to another it3@syamantaka ~]$
directory. cd book
[it3@syamantaka
book]$
To change back to your home [it3@syamantaka
directory: book]$ cd ..
To change back to your home [it3@syamantaka ~]$
directory:
Remove $rmdir filename To remove a directory. [it3@syamantaka ~]$
directory If the directory contains rmdir book
subdirectory or files, then
remove it first and then remove
the directory.

RESULT

Thus the various UNIX commands are executed successfully.

8
EX. NO: 2(a) IMPLEMENTATION OF PROCESS MANAGEMENT USING THE
FOLLOWING SYSTEM CALLS OF UNIX OPERATING SYSTEM: FORK,
EXEC, GETPID, EXIT, WAIT, CLOSE.

AIM:
To write a program for implementing process management using the following
system calls of UNIX operating system: fork, exec, getpid, exit, wait, close.

ALGORITHM:

1. Start the program.


2. Read the input from the command line.
3. Use fork() system call to create process, getppid() system call used to get the parent
process ID and getpid() system call used to get the current process ID
4. execvp() system call used to execute that command given on that command line
argument
5. execlp() system call used to execute specified command.
6. Open the directory at specified in command line input.
7. Display the directory contents.
8. Stop the program.

PROGRAM:

#include<stdio.h>
main(int arc,char*ar[])
{
int pid;
char s[100];
pid=fork();
if(pid<0)
printf("error");

else if(pid>0)

{
wait(NULL);

printf("\n Parent Process:\n");


printf("\n\tParent Process id:%d\t\n",getpid());
execlp("cat","cat",ar[1],(char*)0);

9
error("can’t execute cat %s,",ar[1]);

}
else

{
printf("\nChild process:");
printf("\n\tChildprocess parent id:\t %d",getppid());
sprintf(s,"\n\tChild process id :\t%d",getpid());
write(1,s,strlen(s));
printf(" ");
printf(" ");
printf(" ");
execvp(ar[2],&ar[2]);
error("can’t execute %s",ar[2]);

}
}

OUTPUT:

[root@localhost ~]# ./a.out tst date Child


process:
Child process id :
3137 Sat Apr 10 02:45:32 IST 2010
Parent Process:
Parent Process id:3136 sd
dsaASD[root@localhost ~]# cat tst sd
dsaASD

RESULT:

Thus the program for process management was written and successfully executed.

10
EX.NO: 2b STAT SYSTEM CALL
DATE:

AIM
To display file status using stat system call.
exit()
 The exit system call is used to terminate a process either normally or abnormally
 Closes all standard I/O streams.
stat()
 The stat system call is used to return information about a file as a structure.
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);
11
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" : "-");
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.

12
EX.NO: 2c OPENDIR, READDIR SYSTEM CALLS
AIM
To write a UNIX C program to simulate opendir and readdir system calls.
ALGORITHM
Step 1: Invoke opendir() system call to open a directory by passing command line argument as
parameter.
Step 2: Invoke readdir() system call to read the opened directory.
Step 3:Until the end of directory is encountered, read all the files in directory and display its
directory name,inode number and length of the record.
PROGRAM
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<dirent.h>
main(int argc,char *argv[])
{
DIR *dirname;
struct dirent *dir;
dirname=opendir(argv[1]);
dir=readdir(dirname);
while(dir!=NULL)
{
printf("Entry found :%s\n",dir->d_name);
printf("Inode number of entry:%d\n",dir->d_ino);
printf("Length of this record:%d\n",dir >d_reclen);
getchar();
}
}
OUTPUT
[it1@localhost ~]$ cc ex1f.c
[it1@localhost ~]$ mkdir anu
[it1@localhost ~]$ cd
[it1@localhost ~]$ cd anu
[it1@localhost anu]$ cat>>new
os is an interface
[it1@localhost anu]$ cat>>new1
os is resident monitor
[it1@localhost anu]$ cd
[it1@localhost ~]$ ./a.out anu
Entry found :..
Inode number of entry:26542353
Length of this record:16
RESULT
Thus a UNIX C program to simulate opendir and readdir system calls is executed successfully.
13
EX.NO: 3a CP COMMAND

DATE:

AIM
To simulate cp command using UNIX system call.

ALGORITHM

1. Get source and destination filename as command-line argument.


2. Declare a buffer of size 1KB
3. Open the source file in readonly mode using open system call.
4. If file does not exist, then stop.
5. Create the destination file using creat system call.
6. If file cannot be created, then stop.
7. File copy is achieved as follows:
a. Read 1KB data from source file and store onto buffer using read system
call.
b. Write the buffer contents onto destination file using write system call.
c. If end-of-file then step 8 else step 7a.
8. Close source and destination file using close system call.
9. Stop.

PROGRAM

/* cp command simulation - copy.c */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#define SIZE 1024
main(int argc, char *argv[])
{
int src, dst, nread;
char buf[SIZE];
if (argc != 3)
{
printf("Usage: gcc copy.c -o copy\n");
printf("Usage: ./copy <filename> <newfile> \n");
exit(-1);
}
if ((src = open(argv[1], O_RDONLY)) == -1)

14
{
perror(argv[1]);
exit(-1);
}

if ((dst = creat(argv[2], 0644)) == -1)


{
perror(argv[1]);
exit(-1);
}
while ((nread = read(src, buf, SIZE)) > 0)
{
if (write(dst, buf, nread) == -1)
{
printf("can't write\n");
exit(-1);
}
}

close(src);
close(dst);
}

OUTPUT

$ gcc copy.c -o copy

$ ./copy hello hello.txt

RESULT
Thus a file is copied using file I/O. The cmp command can be used to verify
that contents of both file are same

15
EX.NO: 3b LS COMMAND

DATE:
AIM
To simulate ls command using UNIX system calls.
ALGORITHM
1. Store path of current working directory using getcwd system call.
2. Scan directory of the stored path using scandir system call and sort the
resultant array of structure.
3. Display dname member for all entries if it is not a hidden file.
4. Stop.
PROGRAM

/* ls command simulation - list.c */

#include <stdio.h>
#include <dirent.h>
main()
{
struct dirent **namelist;
int n,i;
char pathname[100];
getcwd(pathname);
n = scandir(pathname, &namelist, 0, alphasort);
if(n < 0)
printf("Error\n");
else
for(i=0; i<n; i++)
if(namelist[i]->d_name[0] != '.')
printf("%-20s", namelist[i]->d_name);
}
OUTPUT

$ gcc list.c -o list

$ ./list
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
RESULT

Thus the filenames/subdirectories are listed, similar to ls command

16
EX.NO: 3c GREP COMMAND
DATE:

AIM
To simulate grep command using UNIX system call.

ALGORITHM

Get filename and search string as command-line argument.


1.
2. Open the file in read-only mode using open system call.
3. If file does not exist, then stop.
4. Let length of the search string be n.
5. Read line-by-line until end-of-file
a. Check to find out the occurrence of the search string in a line by
examining characters in the range 1–n, 2–n+1, etc.
b. If search string exists, then print the line.
6. Close the file using close system call.
7. Stop.
PROGRAM

/* grep command simulation - mygrep.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main(int argc,char *argv[])
{
FILE *fd;
char str[100];
char c;
int i, flag, j, m, k;
char temp[30];
if(argc != 3)
{
printf("Usage: gcc mygrep.c –o mygrep\n");
printf("Usage: ./mygrep <search_text> <filename>\n");
exit(-1);
}
fd = fopen(argv[2],"r");
if(fd == NULL)
{
printf("%s is not exist\n",argv[2]);

17
exit(-1);
}

while(!feof(fd))
{
i = 0;
while(1)
{
c = fgetc(fd);
if(feof(fd))
{
str[i++] = '\0';
break;
}
if(c == '\n')
{
str[i++] = '\0';
break;
}
str[i++] = c;
}
if(strlen(str) >= strlen(argv[1]))
for(k=0; k<=strlen(str)-strlen(argv[1]); k++)
{
for(m=0; m<strlen(argv[1]); m++)
temp[m] = str[k+m];
temp[m] = '\0';
if(strcmp(temp,argv[1]) == 0)
{
printf("%s\n",str);
break;
}
}
}
}
OUTPUT

$ gcc mygrep.c -o mygrep

$ ./mygrep printf dirlist.c


printf("Usage: ./a.out <dirname>\n");
printf("%s\n", dptr->d_name);

RESULT
Thus the program simulates grep command by listing lines containing the search text.

18
EX.NO: 4 SHELL PROGRAMMING
DATE:

AIM
To write simple shell scripts using shell programming fundamentals.

The activities of a shell are not restricted to command interpretation alone. The
shell also has rudimentary programming features. Shell programs are stored in a file
(with extension .sh). Shell programs run in interpretive mode. The original UNIX came
with the Bourne shell (sh) and it is universal even today. C shell (csh) and Korn shell
(ksh) are also widely used. Linux offers Bash shell (bash) as a superior alternative to
Bourne shell.

PRELIMINARIES
1. Comments in shell script start with #.
2. Shell variables are loosely typed i.e. not declared. Variables in an expression or
output must be prefixed by $.
3. The read statement is shell's internal tool for making scripts interactive.
4. Output is displayed using echostatement.
5. Expressions are computed using the expr command. Arithmetic operators are + -
* / %. Meta characters * ( ) should be escaped with a \.
6. The shell scripts are executed
$ sh filename

DECISION-MAKING
Shell supports decision-making using if statement. The if statement like its
counterpart in programming languages has the following formats.

if [ condition ] if [ condition ] if [condition ] then


then then statements
statements statements elif [ condition ]
fi else then
statements statements
fi .. .
else
statements
fi

19
The set of relational operators are –eq –ne –gt –ge –lt –le and logical operators used in
conditional expression are –a –o !

MULTI-WAY BRANCHING
The case statement is used to compare a variables value against a set of
constants. If it matches a constant, then the set of statements followed after ) is
executed till a ;; is encountered. The optional default block is indicated by *. Multiple
constants can be specified in a single pattern separated by |.

casevariable in
constant1)
statements ;;
constant2)
statements ;;
...
*)
statements
esac

LOOPS
Shell supports a set of loops such as for, while and until to execute a set of
statements repeatedly. The body of the loop is contained between do and done
statement.
The for loop doesn't test a condition, but uses a list instead.

forvariable inlist
do
statements
done

The while loop executes the statements as long as the condition remains true.
while [ condition ]
do
statements
done

The until loop complements the while construct in the sense that the statements are
executed as long as the condition remains false.
until [ condition ]
do
statements
done

20
A) SWAPPING VALUES OF TWO VARIABLES
# Swapping values – swap.sh
echo -n "Enter value for A : "
read a
echo -n "Enter value for B : "
read b
t=$a
a=$b
b=$t
echo "Values after Swapping"
echo "A Value is $a and B Value is $b"

OUTPUT
$ sh swap.sh
Enter value for A : 12
Enter value for B : 23
Values after Swapping
A Value is 23 and B Value is 12

B) FARENHEIT TO CENTIGRADE CONVERSION


# Degree conversion – degconv.sh
echo -n "Enter Fahrenheit : "
read f
c=`expr \( $f - 32 \) \* 5 / 9`
echo "Centigrade is : $c"
OUTPUT
$ sh degconv.sh
Enter Fahrenheit : 213
Centigrade is : 100

C) BIGGEST OF 3 NUMBERS
# Biggest – big3.sh
echo -n "Give value for A B and C: "
read a b c
if [ $a -gt $b -a $a -gt $c ]
then
echo "A is the Biggest number"
elif [ $b -gt $c ]
then
echo "B is the Biggest number"
else
echo "C is the Biggest number"
fi
OUTPUT
$ sh big3.sh
Give value for A B and C: 4 3 4
C is the Biggest number

21
D) GRADE DETERMINATION
# Grade – grade.sh
echo -n "Enter the mark : "
read mark
if [ $mark -gt 90 ]
then
echo "S Grade"
elif [ $mark -gt 80 ]
then
echo "A Grade"
elif [ $mark -gt 70 ]
then
echo "B Grade"
elif [ $mark -gt 60 ]
then
echo "C Grade"
elif [ $mark -gt 55 ]
then
echo "D Grade"
elif [ $mark -ge 50 ]
then
echo "E Grade"
else
echo "U Grade"
fi

OUTPUT
$ sh grade.sh
Enter the mark : 65
C Grade

E) VOWEL OR CONSONANT

# Vowel - vowel.sh
echo -n "Key in a lower case character : "
read choice
case $choice in
a|e|i|o|u) echo "It's a Vowel";;
*) echo "It's a Consonant"
esac

OUTPUT
$ sh vowel.
Key in a lower case character : e
It's a Vowel

22
F) SIMPLE CALCULATOR
# Arithmetic operations — calc.sh
echo -n "Enter the two numbers : "
read a b
echo " 1. Addition"
echo " 2. Subtraction"
echo " 3. Multiplication"
echo " 4. Division"
echo -n "Enter the option : "
read option
case $option in
1) c=`expr $a + $b`
echo "$a + $b = $c";;
2) c=`expr $a - $b`
echo "$a - $b = $c";;
3) c=`expr $a \* $b`
echo "$a * $b = $c";;
4) c=`expr $a / $b`
echo "$a / $b = $c";;
*) echo "Invalid Option"
esac

OUTPUT
$ sh calc.sh
Enter the two numbers : 2 4
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter the option : 1
2+4=6

G) MULTIPLICATION TABLE
# Multiplication table – multable.sh
clear
echo -n "Which multiplication table? : "
read n
for x in 1 2 3 4 5 6 7 8 9 10
do
p=`expr $x \* $n`
echo -n "$n X $x = $p"
sleep 1
done
OUTPUT
$ sh multable.sh
Which multiplication table? : 6
6X1=6
6 X 2 = 12
.....
23
H) NUMBER REVERSE
# To reverse a number – reverse.sh
echo -n "Enter a number : "
read n
rd=0
while [ $n -gt 0 ]
do
rem=`expr $n % 10`
rd=`expr $rd \* 10 + $rem`
n=`expr $n / 10`
done
echo "Reversed number is $rd"

OUTPUT
$ sh reverse.sh
Enter a number : 234
Reversed number is 432

I) PRIME NUMBER
# Prime number – prime.sh
echo -n "Enter the number : "
read n
i=2
m=`expr $n / 2`
until [ $i -gt $m ]
do
q=`expr $n % $i`
if [ $q -eq 0 ]
then
echo "Not a Prime number"
exit
fi
i=`expr $i + 1`
done
echo "Prime number"

OUTPUT
$ sh prime.sh
Enter the number : 17
Prime number

RESULT
Thus shell scripts were executed using different programming constructs

24
EX.NO: 5a FCFS SCHEDULING
Date:

AIM
To schedule snapshot of processes queued according to FCFS scheduling.

PROCESS SCHEDULING
 CPU scheduling is used in multiprogrammed operating systems.
 By switching CPU among processes, efficiency of the system can be improved.
 Some scheduling algorithms are FCFS, SJF, Priority, Round-Robin, etc.
 Gantt chart provides a way of visualizing CPU scheduling and enables to
understand better.

FIRST COME FIRST SERVE (FCFS)


 Process that comes first is processed first
 FCFS scheduling is non-preemptive
 Not efficient as it results in long average waiting time.
 Can result in starvation, if processes at beginning of the queue have long bursts.

ALGORITHM
1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime for each process.
4. The wtime for first process is 0.
5. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
6. Compute average waiting time awat and average turnaround time atur
7. Display the btime, ttime and wtime for each process.
8. Display GANTT chart for the above scheduling
9. Display awat time and atur
10. Stop
PROGRAM

/* FCFS Scheduling - fcfs.c */

#include <stdio.h>

struct process

{
int pid;
int btime;
int wtime;
int ttime;
} p[10];
25
main()
{
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ",(i+1));
scanf("%d", &p[i].btime);
p[i].pid = i+1;
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;
printf("\n FCFS Scheduling\n\n");
for(i=0; i<28; i++)
printf("-");
printf("\nProcess B-Time T-Time W-Time\n");
for(i=0; i<28; i++)
printf("-");
for(i=0; i<n; i++)
printf("\n P%d\t%4d\t%3d\t%2d",
p[i].pid,p[i].btime,p[i].ttime,p[i].wtime);
printf("\n");
for(i=0; i<28; i++)
printf("-");
printf("\n\nAverage waiting time: %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("|");
for(i=0; i<n; i++)
{
k = p[i].btime/2;
26
for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" ");
printf("|");
}
printf("\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("0");
for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
}
OUTPUT
Enter no. of process : 4
Burst time for process P1 (in ms) : 10
Burst time for process P2 (in ms) : 4
Burst time for process P3 (in ms) : 11
Burst time for process P4 (in ms) : 6

FCFS Scheduling
----------------------------
Process B-Time T-Time W-Time
----------------------------
P1 10 10 0
P2 4 14 10
P3 11 25 14
P4 6 31 25
----------------------------
Average waiting time : 12.25ms
Average turn around time : 20.00ms

GANTT Chart
----------------------------------------
| P1 | P2 | P3 | P4 |
----------------------------------------
0 10 14 25 31

RESULT
Thus waiting time & turnaround time for processes based on FCFS scheduling was
computed and the average waiting time was determined.
27
EX.NO: 5b SJF SCHEDULING
DATE:

AIM
To schedule snapshot of processes queued according to SJF scheduling.

SHORTEST JOB FIRST (SJF)


 Process that requires smallest burst time is processed first.
 SJF can be preemptive or non–preemptive
 When two processes require same amount of CPU utilization, FCFS is used to
break the tie.
 Generally efficient as it results in minimal average waiting time.
 Can result in starvation, since long critical processes may not be processed.

ALGORITHM
1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime for each process.
4. Sort the processes according to their btime in ascending order.
a. If two process have same btime, then FCFS is used to resolve the tie.
5. The wtime for first process is 0.
6. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
7. Compute average waiting time awat and average turn around time atur.
8. Display btime, ttime and wtime for each process.
9. Display GANTT chart for the above scheduling
10. Display awat and atur
11. Stop
PROGRAM

/* SJF Scheduling – sjf.c */

#include <stdio.h>

struct process
{
int pid;
int btime;
int wtime;
int ttime;
} p[10], temp;
main()
28
{
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ",(i+1));
scanf("%d", &p[i].btime);
p[i].pid = i+1;
}
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if((p[i].btime > p[j].btime) ||
(p[i].btime == p[j].btime && p[i].pid > p[j].pid))
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}

}
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;

printf("\n SJF Scheduling\n\n");


for(i=0; i<28; i++)
printf("-");
printf("\nProcess B-Time T-Time W-Time\n");
for(i=0; i<28; i++)
printf("-");
for(i=0; i<n; i++)
printf("\n P%-4d\t%4d\t%3d\t%2d",
p[i].pid,p[i].btime,p[i].ttime,p[i].wtime);
29
printf("\n");
for(i=0; i<28; i++)
printf("-");
printf("\n\nAverage waiting time: %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n|");
for(i=0; i<n; i++)
{
k = p[i].btime/2;
for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" ");
printf("|");
}
printf("\n-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n0");
for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
}

OUTPUT

Enter no. of process : 5


Burst time for process P1 (in ms) : 10
Burst time for process P2 (in ms) : 6
Burst time for process P3 (in ms) : 5
Burst time for process P4 (in ms) : 6
Burst time for process P5 (in ms) : 9

SJF Scheduling

----------------------------
Process B-Time T-Time W-Time
----------------------------
P3 5 5 0
P2 6 11 5
P4 6 17 11
P5 9 26 17
P1 10 36 26
30
----------------------------

Average waiting time: 11.80ms


Average turn around time : 19.00ms

GANTT Chart
-----------------------------------------------
| P3 | P2 | P4 | P5 | P1 |
-----------------------------------------------
0 5 11 17 26 36

RESULT
Thus waiting time & turnaround time for processes based on SJF scheduling
was computed and the average waiting time was determined.

31
EX.NO: 5c PRIORITY SCHEDULING
DATE:

AIM
To schedule snapshot of processes queued according to Priority scheduling.

PRIORITY
 Process that has higher priority is processed first.
 Prioirty can be preemptive or non–preemptive
 When two processes have same priority, FCFS is used to break the tie.
 Can result in starvation, since low priority processes may not be processed.

ALGORITHM

1. Define an array of structure process with members pid, btime, pri, wtime &
ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime and pri for each process.
4. Sort the processes according to their pri in ascending order.
a. If two process have same pri, then FCFS is used to resolve the tie.
5. The wtime for first process is 0.
6. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
7. Compute average waiting time awat and average turn around time atur
8. Display the btime, pri, ttime and wtime for each process.
9. Display GANTT chart for the above scheduling
10. Display awat and atur
11. Stop
PROGRAM

/* Priority Scheduling- pri.c */

#include <stdio.h>

struct process
{
int pid;
int btime;
int pri;
int wtime;
int ttime;
} p[10], temp;
main()
32
{
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ", (i+1));
scanf("%d", &p[i].btime);
printf("Priority for process P%d : ", (i+1));
scanf("%d", &p[i].pri);
p[i].pid = i+1;
}
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if((p[i].pri > p[j].pri) ||
(p[i].pri == p[j].pri && p[i].pid > p[j].pid) )
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;
printf("\n\t Priority Scheduling\n\n");
for(i=0; i<38; i++)
printf("-");
printf("\nProcess B-Time Priority T-Time W-Time\n");
for(i=0; i<38; i++)
printf("-");
for (i=0; i<n; i++)
printf("\n P%-4d\t%4d\t%3d\t%4d\t%4d",
33
p[i].pid,p[i].btime,p[i].pri,p[i].ttime,p[i].wtime);
printf("\n");
for(i=0; i<38; i++)
printf("-");
printf("\n\nAverage waiting time: %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n|");
for(i=0; i<n; i++)
{
k = p[i].btime/2;
for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" ");
printf("|");
}
printf("\n-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n0");
for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
OUTPUT

Enter no. of process : 5


Burst time for process P1 (in ms) : 10
Priority for process P1 : 3
Burst time for process P2 (in ms) : 7
Priority for process P2 : 1
Burst time for process P3 (in ms) : 6
Priority for process P3 : 3
Burst time for process P4 (in ms) : 13
Priority for process P4 : 4
Burst time for process P5 (in ms) : 5
Priority for process P5 : 2

Priority Scheduling

--------------------------------------
Process B-Time Priority T-Time W-Time
--------------------------------------
34
P2 7 1 7 0
P5 5 2 12 7
P1 10 3 22 12
P3 6 3 28 22
P4 13 4 41 28
--------------------------------------

Average waiting time: 13.80ms


Average turn around time : 22.00ms

GANTT Chart
----------------------------------------------------
| P2 | P5 | P1 | P3 | P4 |
----------------------------------------------------
0 7 12 22 28 41

RESULT
Thus waiting time & turnaround time for processes based on Priority scheduling
was computed and the average waiting time was determined.

35
EX.NO: 5d ROUND ROBIN SCHEDULING
DATE:

AIM
To schedule snapshot of processes queued according to Round robin scheduling.

ROUND ROBIN
 All processes are processed one by one as they have arrived, but in rounds.
 Each process cannot take more than the time slice per round.
 Round robin is a fair preemptive scheduling algorithm.
 A process that is yet to complete in a round is preempted after the time slice
and put at the end of the queue.
 When a process is completely processed, it is removed from the queue.

ALGORITHM
1. Get length of the ready queue, i.e., number of process (say n)
2. Obtain Burst time Bi for each processes Pi.
3. Get the time slice per round, say TS
4. Determine the number of rounds for each process.
5. The wait time for first process is 0.
6. If Bi > TS then process takes more than one round. Therefore turnaround and
waiting time should include the time spent for other remaining processes in
the same round.
7. Calculate average waiting time and turn around time
8. Display the GANTT chart that includes
a. order in which the processes were processed in progression of rounds
b. Turnaround time Ti for each process in progression of rounds.
9. Display the burst time, turnaround time and wait time for each process (in
order of rounds they were processed).
10. Display average wait time and turnaround time
11. Stop
PROGRAM

/* Round robin scheduling- rr.c */


#include <stdio.h>
main()
{
int i,x=-1,k[10],m=0,n,t,s=0;
int a[50],temp,b[50],p[10],bur[10],bur1[10];
int wat[10],tur[10],ttur=0,twat=0,j=0;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d : ", (i+1));
36
scanf("%d", &bur[i]);
bur1[i] = bur[i];
}
printf("Enter the time slice (in ms) : ");
scanf("%d", &t);
for(i=0; i<n; i++)
{
b[i] = bur[i] / t;
if((bur[i]%t) != 0)
b[i] += 1;
m += b[i];
}
printf("\n\t\tRound Robin Scheduling\n");
printf("\nGANTT Chart\n");
for(i=0; i<m; i++)
printf(" ----------------- ");
printf("\n");
a[0] = 0;
while(j < m)
{
if(x == n-1)
x = 0;
else
x++;
if(bur[x] >= t)
{
bur[x] -= t;
a[j+1] = a[j] + t;
if(b[x] == 1)
{
p[s] = x;
k[s] = a[j+1];
s++;
}
j++;
b[x] -= 1;
printf("P%d |", x+1);
}
else if(bur[x] != 0)
{
a[j+1] = a[j] + bur[x];
bur[x] = 0;
if(b[x] == 1)
{
p[s] = x;
k[s] = a[j+1];
s++;
}
j++;
37
b[x] -= 1;
printf("P%d |",x+1);
}
}
printf("\n");
for(i=0;i<m;i++)
printf(" ----------------- ");
printf("\n");
for(j=0; j<=m; j++)
printf("%d\t", a[j]);
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(p[i] > p[j])
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
temp = k[i];
k[i] = k[j];
k[j] = temp;
}
}
}
for(i=0; i<n; i++)
{
wat[i] = k[i] - bur1[i];
tur[i] = k[i];
}
for(i=0; i<n; i++)
{
ttur += tur[i];
twat += wat[i];
}
printf("\n\n");
for(i=0; i<30; i++)
printf("-");
printf("\nProcess\tBurst\tTrnd\tWait\n");
for(i=0; i<30; i++)
printf("-");
for (i=0; i<n; i++)
printf("\nP%-4d\t%4d\t%4d\t%4d", p[i]+1, bur1[i], tur[i],wat[i]);
printf("\n");
for(i=0; i<30; i++)
printf("-");
awat = (float)twat / n;
atur = (float)ttur / n;
38
printf("\n\nAverage waiting time: %.2f ms", awat);
printf("\nAverage turn around time : %.2f ms\n", atur);
}
OUTPUT
Enter no. of process : 5
Burst time for process P1 : 10
Burst time for process P2 : 29
Burst time for process P3 : 3
Burst time for process P4 : 7
Burst time for process P5 : 12
Enter the time slice (in ms) : 10

Round Robin Scheduling

GANTT Chart
--------------------------------------------------------------
P1 | P2 | P3 | P4 | P5 | P2 | P5 | P2 |
--------------------------------------------------------------
0 10 20 23 30 40 50 52 61

------------------------------
Process Burst Trnd Wait
------------------------------
P1 10 10 0
P2 29 61 32
P3 3 23 20
P4 7 30 23
P5 12 52 40
------------------------------
Average waiting time: 23.00 ms
Average turn around time : 35.20 ms

RESULT
Thus waiting time and turnaround time for processes based on Round robin
scheduling was computed and the average waiting time was determined.

39
EX.NO: 6 SEMAPHORE IMPLEMENTATION
DATE:

AIM
To demonstrate the utility of semaphore in synchronization and multithreading.
SEMAPHORE
 The POSIX system in Linux has its own built-in semaphore library.
 To use it, include semaphore.h.
 Compile the code by linking with -lpthread -lrt.
 To lock a semaphore or wait, use the sem_wait function.
 To release or signal a semaphore, use the sem_post function.
 A semaphore is initialised by using sem_init(for processes or threads)
 To declare a semaphore, the data type is sem_t.

ALGORITHM
1. 2 threads are being created, one 2 seconds after the first one.
2. But the first thread will sleep for 4 seconds after acquiring the lock.
3. Thus the second thread will not enter immediately after it is called, it will enter
4 – 2= 2 secs after it is called.
4. Stop.

PROGRAM

/* C program to demonstrate working of Semaphores */

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex;
void* thread(void* arg)
{
//wait
sem_wait(&mutex);
printf("\nEntered..\n");
//critical section
sleep(4);
//signal
printf("\nJust Exiting...\n");
sem_post(&mutex);
}
int main()
{
sem_init(&mutex, 0, 1);
pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL);
sleep(2);
pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL);
40
pthread_join(t2,NULL);
sem_destroy(&mutex);
return 0;
}

OUTPUT

$ gcc sem.c -lpthread

$ ./a.out

Entered..
Just Exiting...
Entered..
Just Exiting...

RESULT
Thus semaphore implementation has been demonstrated.

41
EX.NO: 7a SHARED MEMORY

Date:

AIM
To demonstrate communication between process using shared memory.
SHARED MEMORY
 Two or more processes share a single chunk of memory to communicate
randomly.
 Semaphores are generally used to avoid race condition amongst processes.
 Fastest amongst all IPCs as it does not require any system call.
 It avoids copying data unnecessarily.

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
42
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);
}
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()
{
43
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 = '*';
}
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.

44
EX.NO: 7b(i) INTERPROCESS COMMUNICATION USING PIPES
DATE:

AIM
To write a UNIX C program to implement interprocess communication using pipes.
ALGORITHM
Step 1: Create a pipe structure using pipe() system call.Pipe() system call returns 2 file
descriptors fd[0] and fd[1].fd[0] is opened for reading and fd[1] is opened for writing.
Step 2:Create a child process using fork() system call.
Step 3:Close the read end of the parent process using close().
Step 4:Write the data in the pipe using write().
Step 5:Close the write end of the child process using close().
Step 6:Read the data in the pipe using read()..
PROGRAM
#include<stdio.h>
int main()
{
int fd[2],child;
char a[20];
printf("\nEnter the string to enter into the pipe:");
scanf("%s",a);
pipe(fd);
child=fork();
if(!child)
{
close(fd[0]);
write(fd[1],a,5);
}
else
{
close(fd[1]);
read(fd[0],a,5);
printf("\n The string retrieved from the pipe is %s\n",a);
}
return 0;
}
OUTPUT
[it3@localhost ~]$ vi iiiiiiiiic.c
[it3@localhost ~]$ cc iiiiiiiiic.c
[it3@localhost ~]$ ./a.out
EnTer the string to enter into the pipe:operatingsystem
The string retrieved from the pipe is operatingsystem
RESULT
Thus a UNIX C program to implement interprocess communication using pipes is
executed successfully.

45
EX.NO: 7b(ii) INTERPROCESS COMMUNICATION USING SHARED MEMORY
DATE:

AIM
To write a UNIX C program to implement interprocess communication using shared
memory.

ALGORITHM

Step 1: Start the program.


Step 2: Create the shared memory for parent process using shmget() system call.
Step 3: Attach the shared memory to the child process.
Step 4: Create child process using fork ().
Step 5: Parent process writes the content in the shared memory.
Step 6: The child process reads the content from the shared memory.
Step 7: Detach and release the shared memory.
Step 8: Stop the program.

PROGRAM

#include<stdio.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<fcntl.h>
main()
{
char *shmptr;
int shmid,child,i;
shmid=shmget(2041,30,IPC_CREAT|0666);
shmptr=shmat(shmid,0,0);
child=fork();
if(!child)
{
printf("PARENT WRITING\n");
for(i=0;i<20;i++)
{
shmptr[i]='a'+i;
putchar(shmptr[i]);
}
wait(0);
}
else
{

46
printf("\nCHILD READING\n");
for(i=0;i<20;i++)
putchar(shmptr[i]);
shmdt(NULL);
shmctl(shmid,IPC_RMID,0);
}
}

OUTPUT

[it3@localhost ~]$ vi iiiii.c


[it3@localhost ~]$ cc iiiii.c
[it3@localhost ~]$ ./a.out
PARENT WRITING
abcdefghijklmnopqrst
CHILD READING

RESULT

Thus a UNIX C program to implement interprocess communication using shared memory


is executed successfully.

47
EX.NO: 8 BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE
Date:

AIM
To implement deadlock avoidance by using Banker’s Algorithm.

ALGORITHM
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety or not if we
allow the request.
9. Stop.

PROGRAM

#include <stdio.h>
#include<stdio.h>
main()
{
int r[1][10], av[1][10];
int all[10][10], max[10][10], ne[10][10], w[10],safe[10];
int i=0, j=0, k=0, l=0, np=0, nr=0, count=0, cnt=0;
clrscr();
printf("enter the number of processes in a system");
scanf("%d", &np);
printf("enter the number of resources in a system");
scanf("%d",&nr);
for(i=1; i<=nr; i++)
{
printf("Enter no. of instances of resource R%d " ,i);
scanf("%d", &r[0][i]);
av[0][i] = r[0][i];
}
for(i=1; i<=np; i++)
for(j=1; j<=nr; j++)
all[i][j] = ne[i][j] = max[i][j] = w[i]=0;

48
printf("Enter the allocation matrix");
for(i=1; i<=np; i++)
{
for(j=1; j<=nr; j++)
{
scanf("%d", &all[i][j]);
av[0][j] = av[0][j] - all[i][j];
}
}
printf("Enter the maximum matrix");
for(i=1; i<=np; i++)
{
for(j=1; j<=nr; j++)
{
scanf("%d",&max[i][j]);
}
}
for(i=1; i<=np; i++)
{
for(j=1; j<=nr; j++)
{
ne[i][j] = max[i][j] - all[i][j];
}
}
for(i=1; i<=np; i++)
{
printf("process P%d", i);
for(j=1; j<=nr; j++)
{
printf("\n allocated %d\t",all[i][j]);
printf("maximum %d\t",max[i][j]);
printf("need %d\t",ne[i][j]);
}
printf("\n \n");
}
printf("\nAvailability ");
for(i=1; i<=nr; i++)
printf("R%d %d\t", i, av[0][i]);
printf("\n ");
printf("\n safe sequence");

49
for(count=1; count<=np; count++)
{
for(i=1; i<=np; i++)
{
Cnt = 0;
for(j=1; j<=nr; j++)
{
if(ne[i][j] <= av[0][j] && w[i]==0)
cnt++;
}
if(cnt == nr)
{
k++;
safe[k] = i;
for(l=1; l<=nr; l++)
av[0][l] = av[0][l] + all[i][l];
printf("\n P%d ",safe[k]);
printf("\t Availability ");
for(l=1; l<=nr; l++)
printf("R%d %d\t", l, av[0][l]);
w[i]=1;
}
}
}
getch();
}
OUTPUT

enter the number of processes in a system 3


enter the number of resources in a system 3
enter no. of instances of resource R1 10
enter no. of instances of resource R2 7
enter no. of instances of resource R3 7
Enter the allocation matrix
321
11 2
41 2
Enter the maximum matrix
444
34 5
52 4
process P1
allocated 3 maximum 4 need 1
allocated 2 maximum 4 need 2
allocated 1 maximum 4 need 3

50
process P2
allocated 1 maximum 3 need 2
allocated 1 maximum 4 need 3
allocated 2 maximum 5 need 3

process P3
allocated 4 maximum 5 need 1
allocated 1 maximum 2 need 1
allocated 2 maximum 4 need 2

Availability R1 2 R2 3 R3 2

safe sequence
P3 Availability R1 6 R2 4 R3 4
P1 Availability R1 9 R2 6 R3 5
P2 Availability R1 10 R2 7 R3 7

RESULT
Thus bankers algorithm for dead lock avoidance was executed successfully.

51
EX.NO: 9 IMPLEMENTATION OF DEADLOCK DETECTION ALGORITHM

Date:

AIM
To implement the deadlock detection algorithm.

ALGORITHM
1. Mark each process that has a row in the Allocation matrix of all zeros.
2. Initialize a temporary vectorW to equal the Available vector.
3. Find an indexi such that processi is currently unmarked and thei th row ofQ
4. is less than or equal to W . That is,Q ik … Wk, for 1 … k … m . If no such row is
5. found, terminate the algorithm.
5. If such a row is found, mark processi and add the corresponding row of the
6. allocation matrix to W . That is, setWk = Wk + Aik, for 1 … k … m . Return
7. to step 3.

PROGRAM

#include<stdio.h>
#include<conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;
void input();
void show();
void cal();
main()
{
int i,j;
printf("Deadlock Detection Algo\n");
input();
show();
cal();
getch();
}
void input()
{
int i,j;
printf("Enter the no of Processes\t");
scanf("%d",&n);
printf("Enter the no of resource instances\t");
scanf("%d", &r);
printf("Enter the Max Matrix\n");
for(i=0; i<n; i++)
for(j=0; j<r; j++)
scanf("%d", &max[i][j]);
52
printf("Enter the Allocation Matrix\n");
for(i=0; i<n; i++)
for(j=0; j<r; j++)
scanf("%d", &alloc[i][j]);
printf("Enter the available Resources\n");
for(j=0;j<r;j++)
scanf("%d",&avail[j]);
}
void show()
{
int i, j;
printf("Process\t Allocation\t Max\t Available\t");
for(i=0; i<n; i++)
{
printf("\nP%d\t ", i+1);
for(j=0; j<r; j++)
{
printf("%d ", alloc[i][j]);
}
printf("\t");
for(j=0; j<r; j++)
{
printf("%d ", max[i][j]);
}
printf("\t");
if(I == 0)
{
for(j=0; j<r; j++)
printf("%d ", avail[j]);
}
}
}
void cal()
{
int finish[100], temp, need[100][100], flag=1, k, c1=0;
int dead[100];
int safe[100];
int i, j;
for(i=0; i<n; i++)
{
finish[i] = 0;
/*find need matrix */
for(i=0; i<n; i++)
{
for(j=0; j<r; j++)
{
need[i][j]= max[i][j] - alloc[i][j];
}
}
53
while(flag)
{
flag=0;
for(i=0;i<n;i++)
{
int c=0;
for(j=0;j<r;j++)
{
if((finish[i]==0) && (need[i][j] <= avail[j]))
{
c++;
if(c == r)
{
for(k=0; k<r; k++)
{
avail[k] += alloc[i][j];
finish[i]=1;
flag=1;
}
if(finish[i] == 1)
{
i=n;
}
}
}
}
}
}
J = 0;
Flag = 0;
for(i=0; i<n; i++)
{
if(finish[i] == 0)
{
dead[j] = i;
j++;
flag = 1;
}
}
if(flag == 1)
{
printf("\n\nSystem is in Deadlock and the Deadlock process are\n");
for(i=0;i<n;i++)
{
printf("P%d\t", dead[i]);
}
}
else
{
printf("\n No Deadlock Occur");
54
}
}

OUTPUT

********** Deadlock Detection Algo ************

Enter the no of Processes 3


Enter the no of resource instances 3
Enter the Max Matrix
360
43 3
34 4
Enter the Allocation Matrix
333
20 3
12 4
Enter the available Resources
120
Process Allocation Max Available
P1 333 360 120
P2 203 433
P3 124 344

System is in Deadlock and the Deadlock process are


P0 P1 P2

RESULT
Thus the deadlock detection algorithm has been implemented.

55
EX.NO: 10 THREADING AND SYNCHRONIZATION

DATE:

AIM
To demonstrate threading and synchronization using mutex.

DESCRIPTION
 Thread synchronization is defined as a mechanism which ensures that two or
more concurrent processes or threads do not simultaneously execute some
particular program segment known as critical section.
 Processes’ access to critical section is controlled by using synchronization
techniques.
 When one thread starts executing the critical section (serialized segment
of the program) the other thread should wait until the first thread
finishes.
 If proper synchronization techniques are not applied, it may cause a race
condition where the values of variables may be unpredictable
 A Mutex is a lock that we set before using a shared resource and release after
using it.
 When the lock is set, no other thread can access the locked region of code.
So this ensures a synchronized access of shared resources in the code.

ALGORITHM
1. Create two threads
2. Let the threads share a common resource, say counter
3. Even if thread2 si scheduled to start while thread was not done, access to
shared resource is not done as it is locked by mutex
4. Once thread1 completes, thread2 starts execution
5. Stop

PROGRAM
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* trythis(void *arg)
{
pthread_mutex_lock(&lock);
unsigned long i = 0;
counter += 1;
printf("\n Job %d has started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);

56
printf("\n Job %d has finished\n", counter);
pthread_mutex_unlock(&lock);
return NULL;
}
main()
{
int i = 0;
int error;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &trythis, NULL);
if (error != 0)
printf("\nThread can't be created :[%s]", strerror(error));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);
return 0;
}

OUTPUT

$ gcc filename.c -lpthread

$ ./a.out
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished

RESULT
Thus concurrent threads were synchronized using mutex lock.

57
EX.NO: 11a FIRST FIT ALLOCATION

DATE:

AIM
To allocate memory requirements for processes using first fit allocation.

MEMORY MANAGEMENT
 The first-fit, best-fit, or worst-fit strategy is used to select a free hole from the
set of available holes.

FIRST FIT
 Allocate the first hole that is big enough.
 Searching starts from the beginning of set of holes.

ALGORITHM
1. Declare structures hole and process to hold information about set of holes and
processes respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes, by examining each hole as follows:
a. If hole size > process size then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
b. Otherwise check the next from the set of hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop

PROGRAM

/* First fit allocation - ffit.c */


#include <stdio.h>
struct process
{
int size;
int flag;
int holeid;
} p[10];
struct hole
{
int size;
int actual;
} h[10];
58
main()
{
int i, np, nh, j;
printf("Enter the number of Holes : ");
scanf("%d", &nh);
for(i=0; i<nh; i++)
{
printf("Enter size for hole H%d : ",i);
scanf("%d", &h[i].size);
h[i].actual =h[i].size;
}
printf("\nEnter number of process : " );
scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("enter the size of process P%d : ",i);
scanf("%d", &p[i].size);
p[i].flag = 0;
}
for(i=0; i<np; i++)
{
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <= h[j].size)
{
p[i].flag = 1;
p[i].holeid = j;
h[j].size -= p[i].size;
}
}
}
}
printf("\n\tFirst fit\n");
printf("\nProcess\tPSize\tHole");
for(i=0; i<np; i++)
{
if(p[i].flag != 1)
printf("\nP%d\t%d\tNot allocated", i, p[i].size);
else
printf("\nP%d\t%d\tH%d", i, p[i].size, p[i].holeid);
}

59
printf("\n\nHole\tActual\tAvailable");
for(i=0; i<nh ;i++)
printf("\nH%d\t%d\t%d", i, h[i].actual, h[i].size);
printf("\n");
}

OUTPUT

Enter the number of Holes : 5


Enter size for hole H0 : 100
Enter size for hole H1 : 500
Enter size for hole H2 : 200
Enter size for hole H3 : 300
Enter size for hole H4 : 600
Enter number of process : 4
enter the size of process P0 : 212
enter the size of process P1 : 417
enter the size of process P2 : 112
enter the size of process P3 : 426

First fit

Process PSize Hole


P0 212 H1
P1 417 H4
P2 112 H1
P3 426 Not allocated

Hole Actual Available


H0 100 100
H1 500 176
H2 200 200
H3 300 300
H4 600 183

RESULT
Thus processes were allocated memory using first fit method.

60
EX NO: 11b WORST FIT ALLOCATION
DATE:

AIM:
To allocate memory requirements for processes using worst fit allocation.

ALGORITHM:
1. Create free list as required.
2. Sort the free list in decreasing order of the memory space available.
3. Create allocated list by the following technique:
a. Get the process ID and size required.
b. Fit the process into the space which is the first big enough one.
4. After completion of execution of process, deallocate the allocated space.
5. Print the free space allocated list.

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

OUTPUT:
Enter the number of blocks: 3
Enter the number of files: 2

Enter the size of the blocks:-


Block 1: 5
Block 2: 2
Block 3: 7

Enter the size of the files:-


File 1: 1
File 2: 4

File No File Size Block No Block Size Fragment


1 1 1 5 4
2 4 3 7 3

RESULT:
Thus processes were allocated memory using worst fit method.

62
EX.NO: 11c BEST FIT ALLOCATION

DATE:

AIM
To allocate memory requirements for processes using best fit allocation.

BEST FIT
 Allocate the smallest hole that is big enough.
 The list of free holes is kept sorted according to size in ascending order.
 This strategy produces smallest leftover holes

ALGORITHM
1. Declare structures hole and process to hold information about set of holes and
processes respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes, by examining each hole as follows:
a. Sort the holes according to their sizes in ascending order
b. If hole size > process size then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
c. Otherwise check the next from the set of sorted hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop
PROGRAM
#include <stdio.h>
struct process
{
int size;
int flag;
int holeid;
} p[10];
struct hole
{
int hid;
int size;
int actual;
} h[10];

63
main()
{
int i, np, nh, j;
void bsort(struct hole[], int);
printf("Enter the number of Holes : ");
scanf("%d", &nh);
for(i=0; i<nh; i++)
{
printf("Enter size for hole H%d : ",i);
scanf("%d", &h[i].size);
h[i].actual =h[i].size;
h[i].hid = i;
}
printf("\nEnter number of process : " );
scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("enter the size of process P%d : ",i);
scanf("%d", &p[i].size);
p[i].flag = 0;
}
for(i=0; i<np; i++)
{
bsort(h, nh);
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <= h[j].size)
{
p[i].flag = 1;
p[i].holeid = h[j].hid;
h[j].size -= p[i].size;
}
}
}
}
printf("\n\tBest fit\n");
printf("\nProcess\tPSize\tHole");
for(i=0; i<np; i++)
{
if(p[i].flag != 1)
printf("\nP%d\t%d\tNot allocated", i, p[i].size);
else
printf("\nP%d\t%d\tH%d", i, p[i].size, p[i].holeid);
}
printf("\n\nHole\tActual\tAvailable");
for(i=0; i<nh ;i++)
printf("\nH%d\t%d\t%d", h[i].hid, h[i].actual, h[i].size);

64
printf("\n");
}
void bsort(struct hole bh[], int n)
{
struct hole temp;
int i,j;
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(bh[i].size > bh[j].size)
{
temp = bh[i];
bh[i] = bh[j];
bh[j] = temp;
}
}
}
}

OUTPUT

Enter the number of Holes : 5


Enter size for hole H0 : 100
Enter size for hole H1 : 500
Enter size for hole H2 : 200
Enter size for hole H3 : 300
Enter size for hole H4 : 600
Enter number of process : 4
enter the size of process P0 : 212
enter the size of process P1 : 417
enter the size of process P2 : 112
enter the size of process P3 : 426
Best fit
Process PSize Hole
P0 212 H3
P1 417 H1
P2 112 H2
P3 426 H4

Hole Actual Available


H1 500 83
H3 300 88
H2 200 88
H0 100 100
H4 600 174

RESULT
Thus processes were allocated memory using best fit method.

65
EX.NO: 12 PAGING TECHNIQUE OF MEMORY MANAGEMENT

DATE:

AIM
To determine physical address of a given page using page table.

ALGORITHM
1. Get process size
2. Compte no. of pages available and display it
3. Get relative address
4. Determine the corresponding page
5. Display page table
6. Display the physical address

PROGRAM
#include <stdio.h>
#include <math.h>
main()
{
int size, m, n, pgno, pagetable[3]={5,6,7}, i, j, frameno;
double m1;
int ra=0, ofs;
printf("Enter process size (in KB of max 12KB):");
scanf("%d", &size);
m1 = size / 4;
n = ceil(m1);
printf("Total No. of pages: %d", n);
printf("\nEnter relative address (in hexa) \n");
scanf("%d", &ra);
pgno = ra / 1000;
ofs = ra % 1000;
printf("page no=%d\n", pgno);
printf("page table");
for(i=0;i<n;i++)
printf("\n %d [%d]", i, pagetable[i]);
frameno = pagetable[pgno];
printf("\nPhysical address: %d%d", frameno, ofs);

66
OUTPUT

Enter process size (in KB of max 12KB):12


Total No. of pages: 3
Enter relative address (in hexa):
2643
page no=2
page table
0 [5]
1 [6]
2 [7]
Physical address : 7643

RESULT
Thus physical address for the given logical address is determing using Paging
technique.

67
EX.NO: 13a FIFO PAGE REPLACEMENT
Date:

AIM
To implement demand paging for a reference string using FIFO method.

FIFO
 Page replacement is based on when the page was brought into memory.
 When a page should be replaced, the oldest one is chosen.
 Generally, implemented using a FIFO queue.
 Simple to implement, but not efficient.
 Results in more page faults.
 The page-fault may increase, even if frame size is increased (Belady's anomaly)

ALGORITHM
1. Get length of the reference string, say l.
2. Get reference string and store it in an array, say rs.
3. Get number of frames, say nf.
4. Initalize frame array upto length nf to -1.
5. Initialize position of the oldest page, say j to 0.
6. Initialize no. of page faults, say count to 0.
7. For each page in reference string in the given order, examine:
a. Check whether page exist in the frame array
b. If it does not exist then
i. Replace page in position j.
ii. Compute page replacement position as (j+1) modulus nf.
iii. Increment count by 1.
iv. Display pages in frame array.
8. Print count.
9. Stop

PROGRAM
#include <stdio.h>
main()
{
int i,j,l,rs[50],frame[10],nf,k,avail,count=0;
printf("Enter length of ref. string : ");
scanf("%d", &l);
printf("Enter reference string :\n");
for(i=1; i<=l; i++)
scanf("%d", &rs[i]);
printf("Enter number of frames : ");
scanf("%d", &nf);

68
for(i=0; i<nf; i++)
frame[i] = -1;
j = 0;
printf("\nRef. Str Page frames");
for(i=1; i<=l; i++)
{
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf; k++)
if(frame[k] == rs[i])
avail = 1;
if(avail == 0)
{
frame[j] = rs[i];
j = (j+1) % nf;
count++;
for(k=0; k<nf; k++)
printf("%4d", frame[k]);
}
}
printf("\n\nTotal no. of page faults : %d\n",count);
}
OUTPUT
Enter length of ref. string : 20
Enter reference string :
12342156212376 3
Enter number of frames : 5

Ref. str Page frames


1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
2
1
5 1 2 3 4 5
6 6 2 3 4 5
2
1 6 1 3 4 5
2 6 1 2 4 5
3 6 1 2 3 5
7 6 1 2 3 7
6
3
Total no. of page faults : 10
RESULT
Thus page replacement was implemented using FIFO algorithm.

69
EX.NO: 13b LRU PAGE REPLACEMENT

AIM
To implement demand paging for a reference string using LRU method.

LRU
 Pages used in the recent past are used as an approximation of future usage.
 The page that has not been used for a longer period of time is replaced.
 LRU is efficient but not optimal.
 Implementation of LRU requires hardware support, such as counters/stack.

ALGORITHM
1. Get length of the reference string, say len.
2. Get reference string and store it in an array, say rs.
3. Get number of frames, say nf.
4. Create access array to store counter that indicates a measure of recent usage.
5. Create a function arrmin that returns position of minimum of the given array.
6. Initalize frame array upto length nf to -1.
7. Initialize position of the page replacement, say j to 0.
8. Initialize freq to 0 to track page frequency
9. Initialize no. of page faults, say count to 0.
10. For each page in reference string in the given order, examine:
a. Check whether page exist in the frame array.
b. If page exist in memory then
i. Store incremented freq for that page position in access array.
c. If page does not exist in memory then
i. Check for any empty frames.
ii. If there is an empty frame,
 Assign that frame to the page
 Store incremented freq for that page position in access array.
 Increment count.
iii. If there is no free frame then
 Determine page to be replaced using arrmin function.
 Store incremented freq for that page position in access array.
 Increment count.
iv. Display pages in frame array.
11. Print count.
12. Stop

PROGRAM

/* LRU page replacement - lrupr.c */


#include <stdio.h>
70
int arrmin(int[], int);
main()
{
int i,j,len,rs[50],frame[10],nf,k,avail,count=0;
int access[10], freq=0, dm;
printf("Length of Reference string : ");
scanf("%d", &len);
printf("Enter reference string :\n");
for(i=1; i<=len; i++)
scanf("%d", &rs[i]);
printf("Enter no. of frames : ");
scanf("%d", &nf);
for(i=0; i<nf; i++)
frame[i] = -1;
j = 0;
printf("\nRef. Str Page frames");
for(i=1; i<=len; i++)
{
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf; k++)
{
if(frame[k] == rs[i])
{
avail = 1;
access[k] = ++freq;
break;
}
}
if(avail == 0)
{
dm = 0;
for(k=0; k<nf; k++)
{
if(frame[k] == -1)
dm = 1;
break;
}
if(dm == 1)
{
frame[k] = rs[i];
access[k] = ++freq;
count++;
}
else
{
j = arrmin(access, nf);
frame[j] = rs[i];
access[j] = ++freq;
71
count++;
}
for(k=0; k<nf; k++)
printf("%4d", frame[k]);
}
}
printf("\n\nTotal no. of page faults : %d\n", count);
}
int arrmin(int a[], int n)
{
int i, min = a[0];
for(i=1; i<n; i++)
if (min > a[i])
min = a[i];
for(i=0; i<n; i++)
if (min == a[i])
return i;
}

OUTPUT

Length of Reference string : 15


Enter reference string :
12342 156212 37 63
Enter no. of frames : 5
Ref. str Page frames
1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
2
1
5 1 2 3 4 5
6 1 2 6 4 5
2
1
2
3 1 2 6 3 5
7 1 2 6 3 7
6
3
Total no. of page faults : 8

RESULT
Thus page replacement was implemented using LRU algorithm.

72
EX.NO: 13c IMPLEMENTATION OF LFU PAGE REPLACEMENT ALGORITHM
DATE:

AIM

To write a UNIX C program to implement LFU page replacement algorithm.


ALGORITHM
Step 1: Start the program
Step 2: Declare the size
Step 3: Get the number of frames to be inserted
Step 4: Get the number of pages to be inserted and get the value.
Step 5: Get the page sequence
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 >
#include< conio.h >
struct frame
{
int val;
int freq;
int pos;
}f[30];
int no_frame,no_page,page_seq[100],page_fault=0;
void input()
{
int i;
printf("\n\n least freqently used\n");
printf("\n enter no_of frame");
scanf("%d",&no_frame);
printf("\n enter no_of pages");
scanf("%d",&no_page);
printf("enter page sequence");
for(i=0;i<3;i++)
scanf("%d",&page_seq[i]);
printf("\n");
for(i=0;i<3;i++)
{
f[i].pos=-1;
f[i].val=-1;
f[i].freq=0;
}
}
void display()
{
static int preev_page_fault=0;
int i;
73
for(i=0;i<3;i++)
{
if(f[i].val==-1)
{
printf("0");
}
else
{
printf("%d",f[i].val);
}
}
if(preev_page_fault!=page_fault)
{
printf("F");
preev_page_fault=page_fault;
}
printf("\n");
}
int search(int i)
{
int j;
for(j=0;j<3;j++)
{
if(f[j].val==page_seq[i])
return j;
}
return -1;
}
int position()
{
int i,j=0,k;
for(i=0;i<3;i++)
{
if(f[i].pos==-1)
return i;
}
for(i=0;i<3;i++)
{
if(f[j].freq>f[i].freq)
{
j=i;
}
}
k=j;
for(i=0;i<3;i++)
{
if(f[j].freq==f[i].freq&&j!=i)
{
if(f[j].pos>f[i].pos)
j=i;
74
}
k=j;
return k;
}
return 0;
}
void LFU()
{
int i,k;
input();
for(i=0;i<3;i++)
{
k=search(i);
if(k!=-1)
{
f[k].freq++;
f[k].pos=i;
}
if(k==-1)
{
k=position();
f[k].pos=i;
f[k].val=page_seq[i];
f[k].freq=1;
page_fault++;
}
display();
}
}
void main()
{
clrscr();
LFU();
printf("\n no.of page faults %d",page_fault);
getch();
}
OUTPUT
Least frequently used
Enter no of frame 3
Enter no of pages 4
Enter page sequence 4
5
8
400F
450F
458F
No of page faults 3
RESULT
Thus a UNIX C program to implement LFU page replacement is executed successfully.

75
EX.NO: 14a SINGLE-LEVEL DIRECTORY

DATE:

AIM
To organize files in a single level directory structure, i,e., without sub-directories.

ALGORITHM
1. Get name of directory for the user to store all the files
2. Display menu
3. Accept choice
4. If choice =1 then
Accept filename without any
collission Store it in the directory
5. If choice =2 then
Accept filename
Remove filename from the directory array
6. If choice =3 then
Accept filename
Check for existence of file in the directory array
7. If choice =4 then
List all files in the directory array
8. If choice =5
then Stop

PROGRAM
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct
{
char dname[10];
char fname[25][10];
int fcnt;
}dir;
main()
{
int i, ch;
char f[30];
clrscr();
dir.fcnt = 0;
printf("\nEnter name of directory -- ");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n 1. Create File\t2. Delete File\t3. Search File \n4. Display Files\t5. Exit\n
Enter your choice--");
scanf("%d",&ch);
switch(ch)
{
76
case 1:
printf("\n Enter the name of the file -- ");
scanf("%s", dir.fname[dir.fcnt]);
dir.fcnt++;
break;
case 2:
printf("\n Enter the name of the file -- ");
scanf("%s", f);
for(i=0; i<dir.fcnt; i++)
{
if(strcmp(f, dir.fname[i]) == 0)
{
printf("File %s is deleted ",f);
strcpy(dir.fname[i], dir.fname[dir.fcnt-1]);
break;
}
}
if(I == dir.fcnt)
printf("File %s not found", f);
else
dir.fcnt--;
break;
case 3:
printf("\n Enter the name of the file -- ");
scanf("%s", f);
for(i=0; i<dir.fcnt; i++)
{
if(strcmp(f, dir.fname[i]) == 0)
{
printf("File %s is found ", f);
break;
}
}
if(I == dir.fcnt)
printf("File %s not found", f);
break;
case 4:
if(dir.fcnt == 0)
printf("\n Directory Empty");
else
{
printf("\n The Files are -- ");
for(i=0; i<dir.fcnt; i++)
printf("\t%s", dir.fname[i]);
}
break;
default:
exit(0);
}
77
}
getch();
}

OUTPUT

Enter name of directory -- CSE

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 1
Enter the name of the file -- fcfs

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 1
Enter the name of the file -- sjf

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 1
Enter the name of the file -- lru

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 3
Enter the name of the file -sjf
File sjf is found

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 3
Enter the name of the file bank
File bank is not found

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 4
The Files are --fcfs sjf lru bank

1. Create File 2. Delete File 3. Search File 4. Display Files 5. Exit


Enter your choice -- 2
Enter the name of the file -lru
File lru is deleted

RESULT
Thus files were organized into a single level directory.

78
EX.NO: 14b TWO-LEVEL DIRECTORY
DATE:

AIM
To organize files as two-level directory with each user having his own user file
directory (UFD).

ALGORITHM
1. Display menu
2. Accept choice
3. If choice =1 then
Accept directory name
Create an entry for that directory
4. If choice =2 then
Get directory name
If directory exist then accept filename without collision else report error
5. If choice =3 then
Get directory name
If directory exist then Get filename
If file exist in that directory then delete entry else report error
6. If choice =4 then
Get directory name
If directory exist then Get filename
If file exist in that directory then Display filename else report error
7. If choice =5 then Display files directory-wise
8. If choice =6 then Stop

PROGRAM
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct
{
char dname[10], fname[10][10];
int fcnt;
}dir[10];
main()
{
int i, ch, dcnt, k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n 1. Create Directory\t 2. Create File\t 3.Delete File");
printf("\n 4. Search File \t \t 5. Display \t 6. Exit \n Enter your choice -- ");
scanf("%d", &ch);
79
switch(ch)
{
case 1:
printf("\n Enter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt = 0;
dcnt++;
printf("Directory created");
break;
case 2:
printf("\n Enter name of the directory -- ");
scanf("%s", d);
for(i=0; i<dcnt; i++)
if(strcmp(d,dir[i].dname) == 0)
{
printf("Enter name of the file -- ");
scanf("%s", dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
break;
}
if(i == dcnt)
printf("Directory %s not found",d);
break;
case 3:
printf("\nEnter name of the directory -- ");
scanf("%s", d);
for(i=0; i<dcnt; i++)
{
if(strcmp(d,dir[i].dname) == 0)
{
printf("Enter name of the file -- ");
scanf("%s", f);
for(k=0; k<dir[i].fcnt; k++)
{
if(strcmp(f, dir[i].fname[k]) == 0)
{
printf("File %s is deleted ", f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
80
case 4:
printf("\nEnter name of the directory -- ");
scanf("%s", d);
for(i=0; i<dcnt; i++)
{
if(strcmp(d,dir[i].dname) == 0)
{
printf("Enter the name of the file -- ");
scanf("%s", f);
for(k=0; k<dir[i].fcnt; k++)
{
if(strcmp(f, dir[i].fname[k]) == 0)
{
printf("File %s is found ", f);
goto jmp1;
}
}
printf("File %s not found", f);
goto jmp1;
}
}
printf("Directory %s not found", d);
jmp1: break;
case 5:
if(dcnt == 0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;
default:
exit(0);
}
}
getch();
}
OUTPUT
1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 1
Enter name of directory -- CSE
Directory created

81
1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 1
Enter name of directory -- ECE
Directory created

1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 2
Enter name of the directory --ECE
Enter name of the file -- amruth
File created

1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 2
Enter name of the directory -- CSE
Enter name of the file -- kowshik
File created

1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 2
Enter name of the directory -- CSE
Enter name of the file -- pranesh
File created

1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 2
Enter name of the directory -- ECE
Enter name of the file -- ajith
File created

1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 5
Directory Files
CSE kowshik pranesh
ECE amruth ajith

1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice -- 3
Enter name of the directory -- ECE
Enter name of the file -- ajith
File ajith is deleted

RESULT
Thus user files have been stored in their respective directories and retrieved easily.

82
EX.NO: 15a SEQUENTIAL FILE ALLOCATION
DATE:

AIM
To implement file allocation on free disk space in a contiguous manner.

FILE ALLOCATION
The three methods of allocating disk space are:
1. Contiguous allocation
2. Linked allocation
3. Indexed allocation

CONTIGUOUS
 Each file occupies a set of contiguous block on the disk.
 The number of disk seeks required is minimal.
 The directory contains address of starting block and number of contiguous
block (length) occupied.
 Supports both sequential and direct access.
 First / best fit is commonly used for selecting a hole.

ALGORITHM
1. Assume no. of blocks in the disk as 20 and all are free.
2. Display the status of disk blocks before allocation.
3. For each file to be allocated:
a. Get the filename, start address and file length
b. If start + length > 20, then goto step 2.
c. Check to see whether any block in the range (start, start + length-1) is
allocated. If so, then go to step 2.
d. Allocate blocks to the file contiguously from start block to start + length –
1.
4. Display directory entries.
5. Display status of disk blocks after allocation
6. Stop

PROGRAM
/* Contiguous Allocation - cntalloc.c */
#include <stdio.h>
#include <string.h>
int num=0, length[10], start[10];
char fid[20][4], a[20][4];
void directory()
{
int i;
printf("\nFile Start Length\n");
83
for(i=0; i<num; i++)
printf("%-4s %3d %6d\n",fid[i],start[i],length[i]);
}
void display()
{
int i;
for(i=0; i<20; i++)
printf("%4d",i);
printf("\n");
for(i=0; i<20; i++)
printf("%4s", a[i]);
}
main()
{
int i,n,k,temp,st,nb,ch,flag;
char id[4];
for(i=0; i<20; i++)
strcpy(a[i], "");
printf("Disk space before allocation:\n");
display();
do
{
printf("\nEnter File name (max 3 char) : ");
scanf("%s", id);
printf("Enter start block : ");
scanf("%d", &st);
printf("Enter no. of blocks : ");
scanf("%d", &nb);
strcpy(fid[num], id);
length[num] = nb;
flag = 0;
if((st+nb) > 20)
{
printf("Requirement exceeds range\n");
continue;
}
for(i=st; i<(st+nb); i++)
if(strcmp(a[i], "") != 0)
flag = 1;
if(flag == 1)
{
printf("Contiguous allocation not possible.\n");
continue;
}
start[num] = st;
for(i=st; i<(st+nb); i++)
strcpy(a[i], id);;
printf("Allocation done\n");
num++;
printf("\nAny more allocation (1. yes / 2. no)? : ");
scanf("%d", &ch);
84
} while (ch == 1);
printf("\n\t\t\tContiguous Allocation\n");
printf("Directory:");
directory();
printf("\nDisk space after allocation:\n");
display();
}
OUTPUT

Disk space before allocation:


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Enter File name (max 3 char) : cp
Enter start block : 14
Enter no. of blocks : 3
Allocation done
Any more allocation (1. yes / 2. no)? : 1

Enter File name (max 3 char) : tr


Enter start block : 18
Enter no. of blocks : 3
Requirement exceeds range

Enter File name (max 3 char) : tr


Enter start block : 10
Enter no. of blocks : 3
Allocation done
Any more allocation (1. yes / 2. no)? : 1

Enter File name (max 3 char) : mv


Enter start block : 0
Enter no. of blocks : 2
Allocation done
Any more allocation (1. yes / 2. no)? : 1

Enter File name (max 3 char) : ps


Enter start block : 12
Enter no. of blocks : 3
Contiguous allocation not possible.
Any more allocation (1. yes / 2. no)? : 2
Contiguous Allocation
Directory:
File Start Length
cp 14 3
tr 10 3
mv 0 2
Disk space after allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
mv mv tr tr tr cp cp cp
RESULT
Thus contiguous allocation is done for files with the available free blocks.

85
EX.NO: 15b INDEXED FILE ALLOCATION
DATE :

AIM

To write a UNIX C program to simulate indexed file allocation.

ALGORITHM

Step 1: Start the program.


Step 2: Read the number of files. Step 3: Input the filename.
Step 4: Open the file in read only mode and find start, end and length of the file. Step 5:
Display the name, start, end and length of the file.

PROGRAM

#include<stdio.h>
void main()
{
int f[50],i,k,j,inde[50],n,c,count=0,p;
for(i=0;i<50;i++)
f[i]=0;
x:
printf("Enter the index block\t");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1;
printf("Enter the number of files on index\t");
scanf("%d",&n);
}
else
{
printf("Block already allocated\n");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i]);
for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block already allocated");
goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
printf("\n Allocated");
printf("\n File indexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf("\n Enter 1 to enter more files and 0 to exit\t");
scanf("%d",&c);
if(c==1)
86
goto x;
else
exit(0);
}

OUTPUT

Enter the index block 9


Enter the number of files on index 3
123
Allocated
File indexed
9->1:1
9->2:1
9->3:1
Enter 1 to enter more files and 0 to exit 0

RESULT

Thus a UNIX C program to simulate indexed file allocation scheme is executed


successfully.

87
EX.NO: 15c LINKED FILE ALLOCATION
DATE:

AIM
To implement file allocation on free disk space in linked file allocation.

LINKED
 Each file is a linked list of disk blocks.
 The directory contains a pointer to first and last blocks of the file.
 The first block contains a pointer to the second one, second to third and so on.
 File size need not be known in advance, as in contiguous allocation.
 No external fragmentation.
 Supports sequential access only.

INDEXED
 In indexed allocation, all pointers are put in a single block known as index
block.
 The directory contains address of the index block.
 The ith entry in the index block points to ith block of the file.
 Indexed allocation supports direct access.
 It suffers from pointer overhead, i.e wastage of space in storing pointers.

ALGORITHM
1. Get no. of files
2. Accept filenames and no. of blocks for each file
3. Obtain start block for each file
4. Obtain other blocks for each file
5. Check block availability before allocation
6. If block is unavailable then report error
7. Accept file name
8. Display linked file allocation blocks for that file
9. Stop

PROGRAM

#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
static int b[20], i, j, blocks[20][20];
char F[20][20], S[20], ch;
int sb[20], eb[20], x, n;
clrscr();
printf("\n Enter no. of Files ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter file %d name ::", i+1);
scanf("%s", &F[i]);
88
printf("\n Enter No. of blocks::", i+1);
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
{
printf("\n Enter Starting block of file%d::",i+1);
scanf("%d", &sb[i]);
printf("\nEnter blocks for file%d::\n", i+1);
for(j=0; j<b[i]-1;)
{
printf("\n Enter the %dblock ::", j+2);
scanf("%d", &x);
if(b[i] != 0)
{
blocks[i][j] = x;
j++;
}
else
printf("\n Invalid block::");
}
}
printf("\nEnter the Filename :");
scanf("%s", &S);
for(i=0; i<n; i++)
{
if(strcmp(F[i],S) == 0)
{
printf("\nFname\tBsize\tStart\tBlocks\n");
printf("\n ------------------------------------------------------------------ \n");
printf("\n%s\t%d\t%d\t", F[i], b[i], sb[i]);
printf("%d->",sb[i]);
for(j=0; j<b[i]; j++)
{
if(b[i] != 0)
printf("%d->", blocks[i][j]);
}
}
}
printf("\n ---------------------------------------------------------------------------- \n");
getch();
}

89
OUTPUT

Enter no. of Files ::2

Enter file 1 name ::fcfs


Enter No. of blocks::3

Enter file 2 name ::sjf


Enter No. of blocks::2

Enter Starting block of file1::8


Enter blocks for file1::
Enter the 2 block ::3
Enter the 3 block ::5

Enter Starting block of file2::2


Enter blocks for file2::
Enter the 2 block ::6

Enter the Filename ::fcfs

Fname Bsize Start Blocks


---------------------------------------------
fcfs 3 8 8->3->5
---------------------------------------------

RESULT
Thus blocks for file were allocation using linked allocation method.

90

You might also like