Anda di halaman 1dari 109

Regulation-2013 Academic year-2015-16

EX.NO:1 - BASICSOF UNIX COMMANDS

AU QUESTIONS:

1. Execte the following UNIX commands


a. cat
b. ls
c. grep (grep this file.txt)
d. cat
AIM:
To execute the following UNIX commands.

PRE LAB QUESTIONS:


1.Which symbol will be used with grep command to match the pattern pat at the beginning of a
line?
A. ^pat
B. $pat
C. pat$
D. pat^
E. None of the above
2. Which command is used to sort the lines of data in a file in reverse order
A. sort
B. sh
C. st
D. sort -r
E. None of the above
3. Which command is used to sort the lines of data in a file in reverse order
A. sort
B. sh
C. st
D. sort -r
E. None of the above
4. Which command is used to copy all files having the string chap and any two characters after
that to the progs directory?
A. cp chap?? progs
B. cp chap* progs
C. cp chap[12] /progs/*.*
D. cp chap?? /progs/*
E. None of the above
5. Which command is used to change protection mode of files starting with the string emp and
ending with 1,2, or 3?
A. chmod u+x emp[l-3]
B. chmod 777 emp*
C. chmod u+r ??? emp
D. chmod 222 emp?
E. None of the above

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 1


Regulation-2013 Academic year-2015-16

1. DATE COMMANDS:
SYNTAX : date
USES : Used to display system date and time.
OUTPUT : Thu May 4 15:52:02 IST 2006

OPTIONS:

SYNTAX : date +%m


USES : Used to print the month in number.
OUTPUT : 05

SYNTAX : date +%h


USES : Used to print the month in name.
OUTPUT : May

SYNTAX : date +%y


USES : Used to print the last 2 digits of year.
OUTPUT : 06

SYNTAX : date +%M


USES : Used to displays the time in minute.
OUTPUT : 53

SYNTAX : date +%H


USES : Used to displays the time in hour.
OUTPUT : 15

SYNTAX : date +%a


USES : Used to displays the aggregated form of the day.
OUTPUT : Thu

SYNTAX : date +%r


USES : Used to displays the time in AM or PM.
OUTPUT : 03:54:43 PM

SYNTAX : date +%T


USES : Used to displays the full time in the format of HH:MM:SS.
OUTPUT : 15:55:58

2. CALENDER
SYNTAX : cal
USES : It displays the current month calendar.
OUTPUT :

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 2


Regulation-2013 Academic year-2015-16

May 2006
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

SYNTAX : cal 1998


USES : It displays the mentioned year calendar.
OUTPUT : It will displays the given year calendar.

3. ECHO

SYNTAX : echo UNIX


USES : Used to displaying the given text.
OUTPUT : UNIX

TYPING CONTENT IN MORE THAN ONE LINE

SYNTAX : echo This command


> line exceeds
> a single line"
OUTPUT: This command
line exceeds
a single line
USES : Used to display the multiple line as we entered while executing the
command.

SYNTAX : echo This command \


> line exceeds \
> a single line.
OUTPUT : This command line exceeds a single line.
USES : The Backslash character at the end of each line (followed by
pressing the ENTER key) informs the shell that the user wants to
continue the command on the next line. It is used to display the
multiple lines into single line.
4. BC

SYNTAX : bc
USES : Used to perform simple mathematical calculations. By default this
command accepts decimal numbers and also perform mathematical
calculations on octal and hexadecimal numbers.
OUTPUT :

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 3


Regulation-2013 Academic year-2015-16

1) 5+3
8
2) 1.1+2.2
3.3
3) 3.3-1.2
2.1
4) 5.6*4.1
22.9
5) 8.4/3.2
2
6) 3-1
2
7) 4*5
20
5. WHO

SYNTAX : who
USES : Used to display the login details for all users using the UNIX
systems.
OUTPUT :.
student pts/1 May 4 15:50 (192.168.2.3)
student pts/11 May 4 10:47 (192.168.2.19)
root :0 May 4 14:52 (console)

6. WHO AM I

SYNTAX : who am i
USES : Used to displays the login details of the current users of the system
, who invokes the command.
OUTPUT : student pts/1 May 4 15:50 (192.168.2.3)

7. TTY

SYNTAX : tty(tele type)


USES : It gives the file name of the terminal that you are using , tell you
the device name and the name of the terminal that you currently
working in.
OUTPUT : /dev/pts/1
8. MAN

SYNTAX : man any commmand


USES : It offers the online help facilities and it gives all details for the
particular commands that which user can type file and the directory
commands.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 4


Regulation-2013 Academic year-2015-16

DIRECTORY COMMANDS

9. MAKE DIRECTORY

SYNTAX : mkdir directoryname


USES : Used to create a new directory.
OUTPUT : mkdir jeeva

10. CHANGE DIRECTORY

SYNTAX : cd directory name


USES : Used to change from one working directory to another directory
specified by its argument
OUTPUT : cd jeeva

11. REMOVE DIRECTORY

SYNTAX : rmdir
USES : Used to remove the directory.
OUTPUT : rmdir jeeva

12. PWD

SYNTAX : pwd
USES : Used to display the path that we are working.
OUTPUT : /home/student/vs

FILE & REDIRECTION COMMANDS

13. CAT
SYNTAX : cat > filename
USES : Used to create a new file & insert a content into that file.Press
CTRL + D to exit from that file.
OUTPUT :
cat >sample
flower
jasmine
rose
Press ctrl + d
14. SYNTAX : cat filename
USES : Used to display the content of that file.
OUTPUT :
cat sample
flower
jasmine

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 5


Regulation-2013 Academic year-2015-16

rose

15. SYNTAX : cat < filename1 > filename2


USES : It will copy the content of filename1 to filename2 .the content of
filename to is erased.
OUTPUT :
cat sample1
a
b
c
d
cat <sample >sample1
flower
jasmine
rose

cat sample1
flower
jasmine
rose

16. SYNTAX : cat filename1 filename2 > filename3


USES : The output of filename1 and filename2 are concatenated and stored
in the filename3 , and it is not displayed in the terminal. Here
filename3 is already exits.To view the contents of the file use cat
command.
OUTPUT :
cat sample1 cat sample2
flower ab
jasmine bc
rose d
ef
cat sample3
flower
jasmine
rose
ab
bc
d
ef
17. SYNTAX : any command > filename
USES : The output of any command is stored in the file(filename) and it is
not displayed in the command prompt. To view the output use cat
command.
EX:
SYNTAX : who > sample

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 6


Regulation-2013 Academic year-2015-16

USES : The result of who am i is stored in sample.to view the contents use
cat sample.
OUTPUT:
who > sample4
cat sample4
student pts/1 May 4 15:50 (192.168.2.3)
student pts/11 May 4 10:47 (192.168.2.19)
root :0 May 4 14:52 (console)

APPEND THE FILE CONTENTS

18. SYNTAX : cat filename1 >> filename2


USES : Used to append the contents of filename1 to filename2.
OUTPUT :
cat sample1 cat sample2
flower ab
jasmine bc
rose d
ef
cat sample1 >> sample2
cat sample3
ab
bc
d
ef
flower
jasmine
rose

19. SYNTAX : cat filename1 filename2 >> filename3


USES : The output of filename1 and filename2 are appened in the
filename3 , and it is not displayed in the terminal. Here filename3
is not already exits.It is a new file .so contents are not
overwritten.To view the contents of the file use cat command.

RENAMING THE FILE

20. SYNTAX : mv source filename destination filename


USES : Used to rename thefile.

LIST OUT COMMANDS

21. SYNTAX : ls
USES : Used to list out all files in a directory.

22. SYNTAX : ls -a

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 7


Regulation-2013 Academic year-2015-16

USES : Used to list out all files including hidden files ( Files that begin
with ( . , .. )

23. SYNTAX : ls -i
USES : Used to list out all files with its i-node number in the first column.

24. SYNTAX : ls -r
USES : Used to list out all files in reverse alphabetical order.

25. SYNTAX : ls -t
USES : Used to list out all files in the order of their last modification time.

26. SYNTAX : ls -u
USES : Used to list out all files in the order of their last access time.

27. SYNTAX : ls -l
USES : Used to list out all files in long format ( one entry per line) ,giving
its mode, number of links, owner, group , size in bytes, the time
that each file was last modified.

28. SYNTAX : ls -lt


USES : Used to list out all files in long format with their last modification
time.

FILTER COMMANDS

29. SYNTAX : head -n filename


USES : Used to display the Top n lines of the file.

30. SYNTAX : tail -n filename


USES : Used to display the Bottom n lines of the file.

31. SYNTAX :
more filename
USES :
To see the content of the filename on the screen one page at
a time.
WORD COUNT COMMAND
32. SYNTAX : wc filename
USES : It will display the no of lines , no of words and used to display no
of characters.

33. SYNTAX : wc -l filename


USES : Used to display no of lines in a filename.

34. SYNTAX : wc -w filename


USES : Used to display no of words in a filename.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 8


Regulation-2013 Academic year-2015-16

35. SYNTAX : wc -c filename


USES : Used to display no of Characters in a filename.

COMMON COMMAND

36. SYNTAX : comm. filename1 filenmae2


USES : This command eachline of first file with its corresponding line in
the second file. Output contains 3 columns. First column contains
lines unique to filename1.Second column contains lines unique to
filename2.Third column contains lines common to both.
EX:
$cat n1 $cat nithi
sridhar sridhar
ramamoorthy vikky
mahalashmi vimal
jegan
prhbu

OUTPUT :
$comm n1 nithi
sridhar
vikky
vimal

OPTIONS

37. SYNTAX : comm -1 filename


USES : It doesnt include the first column in output.

38. SYNTAX : comm -2 filename


USES : It doesnt include the second column in output.

39. SYNTAX : comm -3 filename


USES : It doesnt include the third column in output.

COMPARE COMMAND

40. SYNTAX : cmp filename1 filename2


USES : Two files are compared byte by byte and the location of the first
mismatch is echoed in the screen.
OUTPUT :
cmp sample1 sample5
sample1 sample5 differ: byte 7, line 1
41. SYNTAX : cmp l file1 file2
USES : This option gives the detailed list of the byte number and the
differing bytes in octal for each character that differ in both files.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 9


Regulation-2013 Academic year-2015-16

OUTPUT :
cat sample1 cat sample2
flower flower
jasmine carrot
rose papaya
banana
cmp -l sample1 sample5
7 12 40
8 152 12
9 141 143
10 163 141
11 155 162
12 151 162
13 156 157
14 145 164
16 162 160
17 157 141
18 163 160
19 145 141
20 12 171
cmp: EOF on sample1

CUT COMMAND

42. SYNTAX : cut -d any character -f2 filename.


USES : Used to cut the character from first to the specified character from
the file.

OUTPUT :
cat sample1
flower
jasmine
rose

cut -d "w" -f2 sample1


er
jasmine
rose

43. SYNTAX : cut c 1-3 filename


USES : It will command the character which are defined in numbers and it
will displays the character upto that specified number.
OUTPUT :
cat sample5
flower

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 10


Regulation-2013 Academic year-2015-16

carrot
papaya
banana

cut -c 4 sample5
w
r
a
a

COPY COMMAND

44. SYNTAX : cp source filename destination filename


USES : Used to copy the source file contents to destination file contents.

45. PASTE COMMAND

SYNTAX : paste file1 file2


USES : This command merges the contents of 2 files in into a single file. It
reads a line from file in the file list specified and combines them
into a single file.
OUTPUT :
paste sample1 sample2

flower ab
jasmine bc
rose d
ef
flower
jasmine
rose

UNIQUE COMMAND
46. SYNTAX : uniq filename
USES : Used to display the unique lines present in the file.

OUTPUT :
$ cat n1
sridhar
ramamoorthy
mahalashmi
jegan
prhbu
prhbu

$ uniq n1

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 11


Regulation-2013 Academic year-2015-16

sridhar
ramamoorthy
mahalashmi
jegan
prhbu

OPTIONS :

47. SYNTAX : uniq - u filename


USES : Used to display only unique lines present in the file.
OUTPUT :
$ uniq u n1
sridhar
ramamoorthy
mahalashmi
jegan

48. SYNTAX : uniq - d filename


USES : Used to display the duplicate lines in the file.
OUTPUT :
$ uniq d n1
prhbu

49. SYNTAX : uniq - c filename


USES : Used to count the duplicate lines in the file.
OUTPUT :
$ uniq c n1
sridhar
ramamoorthy
mahalashmi
jegan

GREP COMMAND:
SYNTAX: $grep ` ` filename
USE: This command is used to search for a particular pattern from a file or from the
standard input and display those lines on the standard output.
OPTIONS:
50. SYNTAX: $grep v ` ` filename
USE: displays only those lines that do not match the pattern specified.
OUTPUT: name: Bahirathi

51. SYNTAX: $grep c ` ` filename


USE: displays only the count of those lines, which match the pattern, specified.
OUTPUT:
$grep c ` `alamu
3

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 12


Regulation-2013 Academic year-2015-16

52. SYNTAX: $grep n ` ` filename


USE: displays those lines, which match the pattern, specified along with line
number at the beginning of the line
OUTPUT:
$grep n ` ` alamu
1: rathi
3:rgi
5:vrs

53. SYNTAX: $grep i ` ` filename


USE: displays those lines, which match the pattern specified ignoring the case
distinction.
OUTPUT:
$grep i ` ` alamu
Rathi
Raji
vrs

54. PIPE COMMAND :


A pipe is a mechanism, which takes the output of the command as its input for the next
command .

SYNTAX : Command | command


OUTPUT :
$ who |wc -l

55. TEE COMMAND:


SYNTAX : command |tee
USE: used to join pipes and make copies of input .
OUTPUT : $who |tee rs | wc -l

WILD CARDS:
56. *

SYNTAX: $ls *
USE : used in representing any number of characters when used in the prefix or
suffix.

57. ?

SYNTAX : $ls ?
USE : this character is use to represent one character wither in prefix or in suffix of
the filename .

SORTING COMMANDS:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 13


Regulation-2013 Academic year-2015-16

58. Sort :

SYNTAX : $ sort filename


USE : Sort filter arranger input from standard input in alphabetical order .
OUTPUT :
$Sort alamu

OPTIONS:

59. SYNTAX: $ sort r filename


USE : sort command when used with this option will display input taken from
keyboard in reverse alphabetical order .
OUTPUT : sort r alamu
343
56
34
12

60. SYNTAX: $ sort n filename


USE : This option will arrange the input according to numerical and display it .
OUTPUT :
sort n alamu
12
24
56
343

61. SYNTAX: $ sort f filename


USE : digits alphabets and other characters taken as input are converted to ASCII
value . Sort arranges them according to their ASCII value .
OUTPUT :
sort f alamu
*
#
12
24
56
343

62. SYNTAX: $ sort u filename


USE : this option will remove duplicate lines from input and displays as output
OUTPUT :
sort u alamu
Malathi
Raji
Rathi

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 14


Regulation-2013 Academic year-2015-16

Vassanthi
Vrs

63. CHMOD
SYNTAX : $ chmod -w dir name
USE : This command is used to set the three permissions for all the three
categories of users of the file . Only the owner of the file can use it.
OUTPUT:
$ chmod w cs 2 3
Ls l cs 2 3
Total 8
Drwx rwx r-x 2 linux 4096 jun 24 14.46 cs 23

CP COMMAND:
64. SYNTAX : $ cp I filename1 filename 2
USE: This command helps us to create duplicate copies of ordinary file.
OPTIONS: $ cp i filename1 filename2
OUTPUT:
$cp rathi :rs
Cat rs
Name : bahirathi
Roll no: 01 cs 23
3.7.1982

65. SYNTAX : $cp I filename1 filename2


USE: The I ( interactive option , originally warns the users before overwriting
the destination file .

OUTPUT
$cp I rs rathi
cp : overwrite rathi? n
66. SYNTAX: $cp r filename1 filename2
USE : it is now possible to copy an entire directory structures with r ( recursive ) option
OUTPUT
$ cp r rs rathi

67.The path
SYNTAX: $echo PATH
USE: It specifies the current path of the operating system.
OUTPUT:
/bin:/usv/bin:/usr/local/bin

68. Change the password


` Syntax: $ passwd
Use: password can be changed by using passwd command
Output: $ passwd

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 15


Regulation-2013 Academic year-2015-16

UX: passwd: INFO: change password for local


Old password: *****
New password: ******
Re-enter new password: ******
$

RESULT:
Thus the Commands has been executed successfully.

POST LAB QUESTIONS:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 16


Regulation-2013 Academic year-2015-16

1. Which command is used to remove a directory?


A. rd
B. rmdir
C. dldir
D. rdir
E. None of the above

2. Which of the following keys is used to replace a single character with new text?
A. S
B. s
C. r
D. C
E. None of the above

3. Which command is used to extract specific columns from the file?


A. cat
B. cut
C. grep
D. paste
E. None of the above

4. Which command sends the word count of the file infile to the newfile.
A. wc infile >newfile
B. wc <infile >newfile
C. wc infile - newfile
D. wc infile | newfile
E. None of the above

5. Which command is used to remove the read permission of the file 'note' from both the group
and others?
A. chmod go+r note
B. chmod go+rw note
C. chmod go-x note
D. chmod go-r, 4-x note
E. None of the above

EX.NO:2 - SHELL PROGRAMMING

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 17


Regulation-2013 Academic year-2015-16

PRE LAB QUESTIONS:


1. The logout built in command is used to
a) shutdown the computer
b) logoff of the computer
c) logout the current user
d) to exit the current shell

2. The command umask -S


a) prints the current mask using symbolic notation
b) prints the current mask using octal numbers
c) sets the mask to 000
d) sets the mask to 777

3. The mapfile command


a) reads lines of standard input and assigns each to the element of an indexed array
b) reads lines of standard output file
c) reads lines of standard error file
d) none of the mentioned

4. Which option of the kill command sends the given signal name to the specified process?
a) -l
b) -n
c) -s
d) -a

5. Which command puts a script to sleep untill a signal is recieved?


a) sleep
b) suspend
c) disown
d) break

Ex.No.2a - EVEN OR ODD

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 18


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Illustrate how to find even or odd number using shell programming.

AIM:
To write a program to find whether a number is even or odd .

ALGORITHM:
STEP 1: Read the input number.
STEP 2: Perform modular division on input number by 2.
STEP 3: If remainder is 0 print the number is even.
STEP 4: Else print number is odd.
STEP 5: Stop the program.

PROGRAM
echo "enter the number"
read num
echo "enter the number"
read num
if [ `expr $num % 2` -eq 0 ]
then
echo "number is even"
else
echo "number is odd"
fi

OUTPUT:
enter the number: 5
number is odd.

RESULT:
Thus the program has been executed successfully.
Ex.No.2b - BIGGEST OF TWO NUMBERS

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 19


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Illustrate how to find biggest of 2 numbers using shell programming.

AIM :
To write a program to find biggest in two numbers.

ALGORITHM :
STEP 1: Read The Two Numbers.
STEP 2: If Value Of A Is Greater Than B Is Big.
STEP 3: Else Print B Is Big.
STEP 4: Stop The Program.

PROGRAM:
echo "enter the number"
read a b
if [ $a -gt $b ]
then
echo "A is big"
else
echo "B is big"
fi

OUTPUT:
enter the number:
23 67
B is big.

RESULT:
Thus the program has been executed successfully.
Ex.No.2c - BIGGEST OF THREE NUMBERS

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 20


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Write a C program to find largest among 3 numbers using shell programming.

AIM:
To Write a Program to Find Biggest in Three Numbers.

ALGORITHM:
STEP 1: Read The Three Numbers.
STEP 2: If A Is Greater Than B And A Is Greater Than C Then Print A Is Big.
STEP 3: Else If B is greater Than C Then C Is Big.
STEP 4: Else Print C Is Big.
STEP 5: Stop The Program.

PROGRAM:
echo "enter three numbers"
read a b c
if [ $a -gt $b ] && [ $a -gt $c ]
then
echo "A is big"
else if [ $b -gt $c ]
then
echo "B is big"
else
echo "C is big"
fi
fi

OUTPUT:

ENTER THREE NUMBERS:


23 54 78
C IS BIG.

RESULT:
Thus the program has been executed successfully.
Ex.No.2d - FACTORIAL OF A NUMBER

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 21


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Find factorial of a number using shell program

AIM:
To find a factorial of a number using shell script.

ALGORITHM:
Step 1: read a number.
Step 2: Initialize fact as 1.
Step 3: Initialize I as 1.
Step 4: While I is lesser than or equal to no.
Step 5: Multiply the value of I and fact and assign to fact increment the value of I by 1.
Step 6: print the result.
Step 7: Stop the program.

PROGRAM:
echo "Enter the value of N:"
read n
i=$n;
fact=1
while [ $n -gt 0 ]
do
fact=`expr $fact \* $n`
n=`expr $n \- 1`
done
echo "The factorial of $i is $fact"

OUTPUT:
Enter the value of N:
4
The factorial of 4 is 24.

RESULT:

Thus the program has been executed successfull


Ex.No.2e - FIBONACCI SERIES

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 22


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Find the Fibonacci series of a given number using shell programming.

AIM :
To write a program to display the Fibonacci series.

ALGORITHM:

Step 1: Initialize n1& n2 as 0 & 1.


Step 2: enter the limit for Fibonacci.
Step 3: initialize variable as 0
Step 4: Print the Fibonacci series n1 and n2.
Step 5: While the var number is lesser than lim-2
Step 6: Calculate n3=n1+n2.
Step 7: Set n1=n2 and n2=n3
Step 8: Increment var by 1 and print n2
Step 9: stop the program.

PROGRAM:

echo " ENTER THE LIMIT FOR FIBONNACI SERIES"


read lim
n1=0
n2=1
var=0
echo "FIBONACCI SERIES IS "
echo "$n1"
echo "$n2"
while [ $var -lt `expr $lim - 2` ]
do
n3=`expr $n1 + $n2 `
n1=`expr $n2 `
n2=`expr $n3 `
var=`expr $var + 1 `
echo "$n2"
done

OUTPUT

ENTER THE LIMIT FOR FIBONNACI SERIES


5
FIBONACCI SERIES IS
0
1
1
2

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 23


Regulation-2013 Academic year-2015-16

POST LAB QUESTIONS:

1. The command ulimit


a) set a limit on specified resource for system users
b) set/show process resource limit
c) both (a) and (b)
d) none of the mentioned

2. Which of the following commands is used to display the directory attributes rather than its
contents?
a) ls -l -d
b) ls -l
c) ls -x
d) ls -F

3.Which command prints the accumulated user and system times for processes run from the
shell?
a) time
b) times
c) both (a) and (b)
d) none of the mentioned

4. Which command sets up shorthand for command or command line?


a) set
b) alias
c) new
d) echo

5. The command compgen -c shows


a) all variable names
b) all system wide aliases
c) full list of all commands
d) none of the mentioned

RESULT:
Thus the program has been executed successfully.

EX.NO:3 - CPU SCHEDULING ALGORITHM

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 24


Regulation-2013 Academic year-2015-16

PRE LAB QUESTION:

1. Which module gives control of the CPU to the process selected by the short-term scheduler?
a) dispatcher
b) interrupt
c) scheduler
d) none of the mentioned

2. The processes that are residing in main memory and are ready and waiting to execute are kept
on a list called
a) job queue
b) ready queue
c) execution queue
d) process queue

3. The interval from the time of submission of a process to the time of completion is termed as
a) waiting time
b) turnaround time
c) response time
d) throughput

4. Which scheduling algorithm allocates the CPU first to the process that requests the CPU first?
a) first-come, first-served scheduling
b) shortest job scheduling
c) priority scheduling
d) none of the mentioned

5. In priority scheduling algorithm


a) CPU is allocated to the process with highest priority
b) CPU is allocated to the process with lowest priority
c) equal priority processes can not be scheduled
d) none of the mentioned

Ex.No.3a - Round Robin Scheduling Algorithm


AU QUESTION:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 25


Regulation-2013 Academic year-2015-16

1. Take a list of processes, their CPU burst times and arrival times and display the Gantt chart for
Round robin scheduling. Also compute and print the average waiting time and average turn-
around time.
2. Write a C program to implement Round Robin CPU scheduling algorithm with quantum time
5 time units. Processes do not arrive at the same time. Display the following results in a table
format.
i)Arrival time and Burst time of every process.
ii)Waiting time and turnaround time of every process.
iii)Average waiting time and turnaround time.
iv)Total idle time of the processor

AIM:

To compute average waiting time and average turnaround time and to draw Gantt chart using
round-robin scheduling algorithm.

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:
#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++)
{

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 26


Regulation-2013 Academic year-2015-16

printf("Burst time for process P%d : ", (i+1));


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;

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 27


Regulation-2013 Academic year-2015-16

k[s] = a[j+1];
s++;
}
j++;
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++)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 28


Regulation-2013 Academic year-2015-16

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;
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 the C program to compute average waiting time and to display Gantt chart using
Round Robin scheduling is executed and verified successfully.

Ex.No:3b - SHORTEST JOB FIRST SCHEDULING ALGORITHM

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 29


Regulation-2013 Academic year-2015-16

AU QUESTION:
1.Take a list of processes, their CPU burst times and arrival times and display the Gantt chart for
SJF scheduling. Also compute and print the average waiting time and average turn-around time
2. Write a C program to implement Shortest Job First CPU scheduling algorithm where
Processes do not arrive at the same time. Display the following results in a table format.
i)Arrival time and Burst time of every process.
ii)Waiting time and turnaround time of every process.
iii) Average waiting time and turnaround time.
iv) Total idle time of the processor.

AIM:
To compute average waiting time and average turnaround time and to draw Gantt chart using SJF
scheduling algorithm.

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:
#include <stdio.h>
struct process
{
int pid;
int btime;
int wtime;
int ttime;
} p[10], temp;
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++)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 30


Regulation-2013 Academic year-2015-16

{
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);
printf("\n");
for(i=0; i<28; i++)
printf("-");
printf("\n\nGANTT Chart\n");
printf("-");

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 31


Regulation-2013 Academic year-2015-16

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);
}
printf("\n\nAverage waiting time : %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
}

OUTPUT:
Enter no. of process : 5

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 32


Regulation-2013 Academic year-2015-16

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 550
P2 6 11 5
P4 6 17 11
P5 9 26 17
P1 10 3626
----------------------------
GANTT Chart
-----------------------------------------------
| P3 | P2 | P4 | P5 | P1 |
-----------------------------------------------
0 5 11 17 26 36
Average waiting time : 11.80ms
Average turn around time : 19.00ms

RESULT:
Thus the C program to compute average waiting time and to display Gantt chart using
SJF is executed and verified successfully.
Ex.No:3c - FIRST COME FIRST SERVED SCHEDULING ALGORITHM

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 33


Regulation-2013 Academic year-2015-16

AU QUESTION:
Take a list of processes, their CPU burst times and arrival times and display the Gantt chart for
FCFS scheduling. Also compute and print the average waiting time and average turn-around
time.
AIM:
To compute average waiting time and average turnaround time and to draw Gantt chart
using FCFS scheduling algorithm.

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:
#include <stdio.h>
struct process
{
int pid;
int btime;
int wtime;
int ttime;
} p[10];
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++)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 34


Regulation-2013 Academic year-2015-16

{
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\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;
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");

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 35


Regulation-2013 Academic year-2015-16

for(i=0; i<n; i++)


{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
printf("\n\nAverage waiting time : %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
}

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
----------------------------
GANTT Chart
----------------------------------------
| P1 | P2 | P3 | P4 |
----------------------------------------
0 10 14 25 31
Average waiting time : 12.25ms

Result:
Thus the C program to compute average waiting time and to display Gantt chart using
FCFS is executed and verified successfullty.
Ex.No:3d - PRIORITY SCHEDULING ALGORITHM

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 36


Regulation-2013 Academic year-2015-16

AU QUESTION:
Take a list of processes, their CPU burst times and arrival times and display the Gantt chart for
Priority based Scheduling. Also compute and print the average waiting time and average turn-
around time.

AIM:
To compute average waiting time and average turnaround time and to draw Gantt chart using
priority scheduling algorithm.

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:
#include <stdio.h>
struct process
{
int pid;
int btime;
int pri;
int wtime;
int ttime;
} p[10], temp;
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);
printf("Priority for process P%d : ", (i+1));

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 37


Regulation-2013 Academic year-2015-16

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",
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\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 38


Regulation-2013 Academic year-2015-16

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);
}
printf("\n\nAverage waiting time : %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
}

OUTPUT:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 39


Regulation-2013 Academic year-2015-16

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
--------------------------------------------------
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
--------------------------------------
GANTT Chart
----------------------------------------------------
| P2 | P5 | P1 | P3 | P4 |
----------------------------------------------------
0 7 12 22 28 41
Average waiting time : 13.80ms
Average turn around time : 22.00ms

Result:

Thus the C program to compute average waiting time and to display Gantt chart using
Priority scheduling is executed and verified successfully.

POST LAB QUESTION:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 40


Regulation-2013 Academic year-2015-16

1. In priority scheduling algorithm, when a process arrives at the ready queue, its priority is
compared with the priority of
a) all process
b) currently running process
c) parent process
d) init process

2. The strategy of allowing processes that are logically runnable to be temporarily suspended is
called
a) non preemptive scheduling
b) preemptive scheduling
c) priority scheduling algorithm
d) multilevel queue scheduling algorithm

3. In round robin CPU scheduling as time quantum is increased the average turn around time
a) increases
b) decreases
c) remains constant
d) varies irregularly

4. Round robin scheduling is essentially the preemptive version of ________


a) FIFO
b) Shortest job first
c) Shortest remaining
d) Priority

5. Which of the following statements are true?


I. Shortest remaining time first scheduling may cause starvation
II. Preemptive scheduling may cause starvation
III. Round robin is better than FCFS in terms of response time
a) I only
b) I and III only
c) II and III only
d) I, II and III

EX.NO:4 - FILE ALLOCATION STRATEGIES

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 41


Regulation-2013 Academic year-2015-16

PRE LAB QUESTION:


1.A better way of contiguous allocation to extend the file size is :
a) adding an extent (another chunk of contiguous space)
b) adding an index table to the first contiguous block
c) adding pointers into the first contiguous block
d) None of these

2) If the extents are too large, then the problem that comes in is
a) internal fragmentation
b) external fragmentation
c) starvation
d) All of these

3) The FAT is used much as a _________.


a) stack
b) linked list
c) data
d) pointer

4) A section of disk at the beginning of each partition is set aside to contain the table in :
a) FAT
b) linked allocation
c) Hashed allocation
d) indexed allocation

5) Contiguous allocation has two problems _________ and _________ that linked allocation
solves.
a) external fragmentation
b) internal fragmentation
c) size declaration
d) memory allocation

Ex.No:4a - SEQUENTIAL FILE ALLOCATION STRATEGY

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 42


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Write a C program to arrange the file in sequential order

AIM:
To write a program to implement the Sequential File Allocation Strategy

ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order
a). Randomly select a location from available location.
b). Check whether the required locations are free from the selected location.
c). Allocate the file to the free space sequentially.
Step 5: Print the results fileno, length and Blocks allocated.
Step 6: Stop the program

PROGRAM:
#include <stdio.h>
#include <conio.h>
main()
{
int f[50],i,st,j,len,c,k;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
X:
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1)
goto X;

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 43


Regulation-2013 Academic year-2015-16

else
exit();
getch();
}

OUTPUT:
Enter the starting block & length of file: 4 10
4->1
5->1
6->1
7->1
8->1
9->1
10->1
11->1
12->1
13->1
the file is allocated to disk
if u want to enter more files?(y-1/n-0)

Result:
Thus the C program for sequential file allocation technique is executed and verified
successfully.

Ex.No:4b - INDEXED FILE ALLOCATION STRATEGY

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 44


Regulation-2013 Academic year-2015-16

AU QUESTION:
Write a C program to implement Indexed File allocation technique.

AIM:
To implement File allocation technique using Indexed method.

ALGORITHM:

Step 1: Start the program.


Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each based on index
a). Randomly select a location from available location.
b). Check whether the required locations are free from the selected location.
c). Allocate the file to the free space with the index value.
Step 5: Print the results fileno, length and Blocks allocated.
Step 6: Stop the program

PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],b[20][20],x;
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("Enter starting block and size of file%d:",i+1);
scanf("%d%d",&sb[i],&s[i]);
printf("Enter blocks occupied by file%d:",i+1);
scanf("%d",&m[i]);
printf("enter blocks of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
}
printf("\nFile\t index\tlength\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);
}
printf("\nEnter file name:");
scanf("%d",&x);
printf("file name is:%d\n",x);
i=x-1;

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 45


Regulation-2013 Academic year-2015-16

printf("Index is:%d",sb[i]);
printf("Block occupied are:");
for(j=0;j<m[i];j++)
printf("%3d",b[i][j]);
getch();
}

OUTPUT:
Enter no. of files:2
Enter starting block and size of file1: 2 5
Enter blocks occupied by file1:10
enter blocks of file1:3
2 5 4 6 7 2 6 4 7
Enter starting block and size of file2: 3 4
Enter blocks occupied by file2:5
Enterblocks of file2: 2 3 4 5 6
File index length
1 2 10
2 3 5
Enter file name: venkat
file name is:12803
Index is: 0

Result:

Thus the C program for Indexed File allocation technique is executed and verified
successfully.

Ex.No:4c - LINKED FILE ALLOCATION STRATEGY

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 46


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Write a C program to implement Linked File allocation technique.

AIM:

To implement Linked File allocation technique.

ALGORITHM:

Step 1: Start the program.


Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required memory locations to each file
a). Randomly select a location from available location.
b). Allocate the file to the free space with the specified block size
Step 5: Print the results fileno, length and Blocks allocated.
Step 6: Stop the program

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
main()
{
int i,j,n;
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",&f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 47


Regulation-2013 Academic year-2015-16

}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);
for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
}
getch();
}

OUTPUT:
Enter no. of files:2
Enter file name:venkat
Enter starting block:20
Enter no.of blocks:6
Enter block numbers: 4
12
15
45
32
25
Enter file name:raj
Enter starting block:12
Enter no.of blocks:5
Enter block numbers:6
5
4
3
2
File start size block
venkat 20 6 4--->12--->15--->45--->32--->25
rajesh 12 5 6--->5--->4--->3--->2

Result:
Thus the C programs for File allocation technique are executed and verified successfully.

POST LAB QUESTIONS:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 48


Regulation-2013 Academic year-2015-16

1) Each _______ has its own index block.


a) partition
b) address
c) file
d) All of these

2) Indexed allocation _________ direct access.


a) supports
b) does not support
c) is not related to
d) None of these

3) The pointer overhead of indexed allocation is generally _________ the pointer overhead
of linked allocation.
a) less than
b) equal to
c) greater than
d) keeps varying with

4) For any type of access, contiguous allocation requires ______ access to get a disk block.
a) only one
b) atleast two
c) exactly two
d) None of these

5) Consider a disk where blocks 2,3,4,5,8,9,10,11,12,13,17,18,25,26 and 27 are free and the
rest of the blocks are allocated. Then the free space bit map would be :
a) 10000110000001110011111100011111
b) 110000110000001110011111100011111
c) 01111001111110001100000011100000
d) 001111001111110001100000011100000

EX:NO:5 IMPLEMENTATION OF SEMAPHORES


(PRODUCER- CONSUMER PROBLEM)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 49


Regulation-2013 Academic year-2015-16

AU QUESTION:
Implement a program using system calls to demonstrate Producer- Consumer problem using
binary semaphores

AIM:
To implement the Producer- Consumer problem using semaphores.

PRE LAB QUESTION:


1. An un-interruptible unit is known as
a) single
b) atomic
c) static
d) None of these

2. The TestAndSet instruction is executed


a) after a particular process
b) periodically
c) atomically
d) None of these

3) Semaphore is an _______ to solve the critical section problem.


a) hardware for a system
b) special program for a system
c) integer variable
d) None of these

4) The two atomic operations permissible on semaphores are : (choose two)


a) wait
b) stop
c) hold
d) signal

5)Spinlocks are :
a) CPU cycles wasting locks over critical sections of programs
b) locks that avoid time wastage in context switches
c) locks that work better on multiprocessor systems
d) All of these

ALGORITHM:

1. Start the program.

2. Using the segment system call create a semaphore.

3. Using semctrl system call initialize semaphore values.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 50


Regulation-2013 Academic year-2015-16

4. Create a process using fork system call.

5. If the process is parent then print producer with id and create the delay in
proceeding by using rand() and RAND-MAX system call.

6. If the process is child then realize the semaphore and execute it.

7. Print the producer and consumer.

8. Stop the program.

Program:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<unistd.h>
#include<time.h>
#define N 8
int pc=1;
main()
{
int semval=0,pid,cpid,i,rc;
struct sembuf sb;
struct timespec delay;
int semid=semget(IPC_PRIVATE,1,0600);
semval=0;
rc=semctl(semid,0,SETVAL,semval);
pid=fork();
switch(pid)
{
case 0:
for(i=0;i<N;i++)
{
sb.sem_num=0;
sb.sem_op=-1;
sb.sem_flg=0;
semop(semid,&sb,1);
printf("\n consumer consumed the item%d",pc++);
fflush(stdout);
}
break;
case 1:
printf("cant fork");

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 51


Regulation-2013 Academic year-2015-16

exit(0);break;
default:
for(i=0;i<N;i++){
fflush(stdout);
sb.sem_num=0;
sb.sem_op=1;
sb.sem_flg=0;
semop(semid,&sb,1);
printf("\n producer produced the item%d",pc++);
if(rand()>3*(RAND_MAX/4))
{
delay.tv_sec=0;
delay.tv_nsec=10;
nanosleep(&delay,NULL);
}
}
break;
}
printf("\n");
}

OUTPUT:
[CSEII51@arec ~]$ cc pc.c
[CSEII51@arec ~]$ ./a.out

consumer consumed the item1


producer produced the item1
producer produced the item2

consumer consumed the item2


consumer consumed the item3
producer produced the item3

consumer consumed the item4


producer produced the item4

consumer consumed the item5


producer produced the item5
producer produced the item6
producer produced the item7

consumer consumed the item6


consumer consumed the item7
consumer consumed the item8
producer produced the item8
[CSEII51@arec ~]$

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 52


Regulation-2013 Academic year-2015-16

Result:
Thus the C program for Producer Consumer problem using semaphore is executed and
verified successfully.
POST LAB QUESTION:
1) What will happen if a non-recursive mutex is locked more than once ?
a) Starvation
b) Deadlock
c) Aging
d) Signaling

2) To avoid the race condition, the number of processes that may be simultaneously inside
their critical section is
a) 8
b) 1
c) 16
d) 0

3) The two kinds of semaphores are : (choose two)


a) mutex
b) binary
c) counting
d) decimal

4) A mutex :
a) is a binary mutex
b) must be accessed from only one process
c) can be accessed from multiple processes
d) None of these

5) At a particular time of computation the value of a counting semaphore is 7.Then 20 P


operations and 15 V operations were completed on this semaphore.The resulting value of
the semaphore is :
a) 42
b) 2
c) 7
d) 12

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 53


Regulation-2013 Academic year-2015-16

EX.NO:6 IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUES

PRE LAB QUESTION:


1. ______ is a unique tag, usually a number, identifies the file within the file system.
a) File identifier
b) File name
c) File type
d) none of the mentioned

2. To create a file
a) allocate the space in file system
b) make an entry for new file in directory
c) both (a) and (b)
d) none of the mentioned

3. Which of the following file name extension suggests that the file is Backup copy of
another file ?
a) TXT
b) COM
c) BAS
d) BAK

4. File type can be represented by


a) file name
b) file extension
c) file identifier
d) none of the mentioned

5. Which file is a sequence of bytes organized into blocks understandable by the systems
linker?
a) object file
b) source file
c) executable file
d) text file

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 54


Regulation-2013 Academic year-2015-16

EXNO: 6a IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUE BY


SINGLE LEVEL DIRECTORY
AU QUESTIONS:
Illustrate how file organization is done with single level directory technique

AIM:

To write a program to simulate Single level directory file organization technique.

ALGORITHM:
Step 1:Start
Step2: Initialize values gd=DETECT,gm,count,i,j,mid,cir_x; Initialize character array
fname[10][20];
Step 3: Initialize graph function as Initgraph(& gd, &gm," c:/tc/bgi");
Step 4: Set back ground color with setbkcolor();
Step 5: Read number of files in variable count.
Step 6:check if i<count
Step 7: for i=0 & i<count, increment i;
Cleardevice();
setbkcolor(GREEN);
read file name;
setfillstyle(1,MAGENTA);

Step 8: Assign a value to mid as mid=640/count;


cir_x=mid/3;
bar3d(270,100,370,150,0,0);
settextstyle(2,0,4);
settextstyle(1,1);
outtextxy(320,125,"rootdirectory");
setcolor(BLUE); i++;

Step 9:for j=0&&j<=i&&cir_x+=mid


j increment;
line(320,150,cir_x,250);
fillellipse(cir_x,250,30,30);
outtextxy(cir_x,250,fname[i]);
Step 10: End

PROGRAM:
#include<stdio.h>

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 55


Regulation-2013 Academic year-2015-16

#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm,count,i,j,mid,cir_x;
char fname[10][20];
clrscr();
initgraph(&gd,&gm,"c:\tc\bgi");
cleardevice();
setbkcolor(GREEN);
puts("Enter no of files do u have?");
scanf("%d",&count);
for(i=0;i<count;i++)
{
cleardevice();
setbkcolor(GREEN);
printf("Enter file %d name",i+1);
scanf("%s",fname[i]);
setfillstyle(1,MAGENTA);
mid=640/count;
cir_x=mid/3;
bar3d(270,100,370,150,0,0);
settextstyle(2,0,4);
settextjustify(1,1);
outtextxy(320,125,"Root Directory");
setcolor(BLUE);
for(j=0;j<=i;j++,cir_x+=mid)
{
line(320,150,cir_x,250);
fillellipse(cir_x,250,30,30);
outtextxy(cir_x,250,fname[j]);
}
getch();
}
}

OUTPUT:
Enter no of files do u have? 1
Enter file 1 name: 1.c

Result:

Thus the C program for File organization technique using single level directory

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 56


Regulation-2013 Academic year-2015-16

is executed and verified successfully.

EXNO: 6b IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUE BY TWO


LEVEL DIRECTORY
AU QUESTIONS:
Illustrate how file organization is done using two level directory technique

AIM:

To write a program to simulate Two level file organization technique.

ALGORITHM:

Step 1:Start
Step 2: Initialize structure elements
Step 3: Start main function
Step 4: Declare the graphics variables gd=DETECT and gm;
Step 5: Create root directory
Step 6: Set the path for the sub directories
Step 7: Allocate the files in memory
Step 8: Display the path and files

PROGRAM:

#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"null",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\tc\bgi");
display(root);
getch();
closegraph();

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 57


Regulation-2013 Academic year-2015-16

}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node*)malloc(sizeof(node));
printf("enter name of dir/file(under %s):",dname);
fflush(stdin);
gets((*root)->name);
if(lev==0||lev==1)
(*root)->ftype=1;
else
(*root)->ftype=2;
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x; (*root)- >lx=lx; (*root)->rx=rx;
for(i=0;i<5;i++) \
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
if(lev==0||lev==1)
{
if((*root)->level==0)
printf("How many users");
else
printf("how many files");
printf("(for%s):",(*root)->name);
scanf("%d",&(*root)->nc);
}
else (*root)->nc=0; if((*root)->nc==0) gap=rx-lx;
else gap=(rx-lx)/(*root)->nc; for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 58


Regulation-2013 Academic year-2015-16

for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
display(root->link[i]);
}
}
}

OUTPUT:

enter name of dir/file(under null):sld


How many users(forsld):2
enter name of dir/file(under sld):tld
How many files(fortld):2
enter name of dir/file(under tld):hir
enter name of dir/file(under tld):dag
enter name of dir/file(under sld):bin
How many files(forbin):2
enter name of dir/file(under bin):exe
enter name of dir/file(under bin):obj

RESULT:

Thus the C program for File organization technique using two level directories

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 59


Regulation-2013 Academic year-2015-16

is executed and verified successfully.


EXNO: 6c IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUE BY
HIERARCHICAL LEVEL DIRECTORY

AU QUESTIONS:
Illustrate how file organization is done with hierarchical level directory file organization
technique

AIM:

To write a program to simulate Hierarchical level file organization technique

ALGORITHM:

Step 1:Start
Step 2: Initialize structure elements
Step 3: Start main function
Step 4: Declare the graphics variables gd=DETECT and gm;
Step 5: Create root directory
Step 6: Set the path for the sub directories
Step 7: Allocate the files in memory
Step 8: Display the path and files

PROGRAM:

#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_elementnode;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\tc\BGI");
display(root);
getch();
closegraph();

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 60


Regulation-2013 Academic year-2015-16

}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("Enter name of dir/file(under %s) : ",dname); fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for file :");
scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;

(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("No of sub directories/files(for %s):",(*root)->name); scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root !=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name); for(i=0;i<root->nc;i++)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 61


Regulation-2013 Academic year-2015-16

{
display(root->link[i]);
}
}
}

OUTPUT:

Enter Name of dir/file (under root):


ROOT Enter 1 for Dir / 2 For File : 1
No of subdirectories / files (for ROOT) :2
Enter Name of dir/file (under ROOT):
USER 1 Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER 1): 1
Enter Name of dir/file (under USER
1):SUBDIR Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR): 2
Enter Name of dir/file (under USER
1):JAVA Enter 1 for Dir /2 for file:1
No of subdirectories /files (for JAVA): 0
Enter Name of dir/file (under
SUBDIR):VB Enter 1 for Dir /2 for file:1
No of subdirectories /files (for VB): 0
Enter Name of dir/file (under
ROOT):USER2 Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER2): 2
Enter Name of dir/file (under
ROOT):A Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under USER2):SUBDIR
2 Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR 2):
2 Enter Name of dir/file (under
SUBDIR2):PPL Enter 1 for Dir /2 for file:1
No of subdirectories /files (for PPL):
2 Enter Name of dir/file (under
PPL):B Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under
PPL):C Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under SUBDIR):AI
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for AI): 2
Enter Name of dir/file (under AI):D
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under AI):E
Enter 1 for Dir /2 for file:2

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 62


Regulation-2013 Academic year-2015-16

Result:

Thus the C program for File organization technique using hierarchical level directory is
executed and verified successfully.
EXNO: 6d IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUE BY DAG

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 63


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Illustrate how file organization is done with DAG

AIM:

To write a program to implement the implement file organization techniques by DAG.

ALGORITHM:

Step 1:Start
Step 2: Initialize structure elements
Step 3: Start main function
Step 4: Declare graphics variables gd=DETECT and gm;
Step 5: Get the number of links
Step 6: Define the method to draw links between the files
Step 7: Allocate the files in memory and print the number of directories and sub directories
Step 8: Display the constructed DAG
Step 9: End

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_elementnode;
typedef struct
char from[20];
char to[20];
}link;
link L[10];
int nofl;
node * root;
void main()
{
int gd=DETECT,gm;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
read_links();

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 64


Regulation-2013 Academic year-2015-16

clrscr();
initgraph(&gd,&gm,"c:\tc\BGI");
draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
int i;
printf("how many links");
scanf("%d",&nofl);
for(i=0;i<nofl;i++)
{
printf("File/dir:");
fflush(stdin);
gets(L[i].from);
printf("user name:");
fflush(stdin);
gets(L[i].to);
}
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
}
search(node *root,char *s, int *x,int *y)
{
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
IT
{
*x=root->x;
*y=root->y;

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 65


Regulation-2013 Academic year-2015-16

return;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y);
}
}
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("enter name of dir/file(under %s):",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for dir/ 2 for file:");
scanf("%d",&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("no of sub directories /files (for %s):",(*root)->name);
scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create( & ( (*root)->link[i] ) , lev+1 ,
(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}
}
/* displays the constructed tree in graphics mode */
display(node *root)
{

int i;

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 66


Regulation-2013 Academic year-2015-16

settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root !=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}}}

OUTPUT:
Enter Name of dir/file (under root): ROOT
Enter 1 for Dir / 2 For File : 1
No of subdirectories / files (for ROOT) :2
Enter Name of dir/file (under ROOT): USER 1
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER 1): 2
Enter Name of dir/file (under USER1): VB
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for VB): 2
Enter Name of dir/file (under VB): A
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under VB): B
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under USER1): C
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under ROOT): USER2
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER2): 1
Enter Name of dir/file (under USER2):JAVA
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for JAVA):2
Enter Name of dir/file (under JAVA):D
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under JAVA):HTML
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for HTML):0
How many links:2

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 67


Regulation-2013 Academic year-2015-16

File/Dir: B
User Name: USER 2
File/Dir: HTML
User Name: USER1

Result:
Thus the C program for File organization technique using direct acyclic is executed and
verified successfully
POST LAB QUESTIONS:

1. What is meant by mounting of file system?

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 68


Regulation-2013 Academic year-2015-16

a) crating of a filesystem
b) deleting a filesystem
c) attaching portion of the file system into a directory structure
d) removing portion of the file system into a directory structure

2. Mapping of file is managed by


a) file metadata
b) page table
c) virtual memory
d) file system

3. Mapping of network file system protocol to local file system is done by


a) network file system
b) local file system
c) volume manager
d) remote mirror

4. Which one of the following explains the sequential file access method?
a) Random access according to the given byte number
b) read bytes one at a time, in order
c) read/write sequentially by record
d) read/write randomly by record

5. File system fragmentation occurs when


a) unused space or single file are not contiguous
b) used space is not contiguous
c) unused space is non-contiguous
d) multiple files are non-contiguous

EXNO: 7 IMPLEMENTATION OF BANKERS ALGORITHM FOR DEAD LOCK


AVOIDANCE

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 69


Regulation-2013 Academic year-2015-16

AU QUESTIONS:
Implement Deadlock avoidance technique using bankers algorithm

AIM:

To write a program to implement the Bankers Algorithm for Dead Lock Avoidance

PRE LAB QUESTIONS:


1) If no cycle exists in the resource allocation graph :
a) then the system will not be in a safe state
b) then the system will be in a safe state
c) either a or b
d) None of these

2) Given a priori information about the ________ number of resources of each type that
maybe requested for each process, it is possible to construct an algorithm that ensures that
the system will never enter a deadlock state.
a) minimum
b) average
c) maximum
d) approximate

3) A deadlock avoidance algorithm dynamically examines the __________, to ensure that a


circular wait condition can never exist.
a) resource allocation state
b) system storage state
c) operating system
d) resources

4) A state is safe, if :
a) the system does not crash due to deadlock occurrence
b) the system can allocate resources to each process in some order and still avoid a
deadlock
c) the state keeps the system protected and safe
d) All of these

5) A system is in a safe state only if there exists a :


a) safe allocation
b) safe resource
c) safe sequence
d) All of these

ALGORITHM:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 70


Regulation-2013 Academic year-2015-16

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 safe mode.
9. If not allow the request.
10.Stop the program.
11. End

PROGRAM:

#include< stdio.h >


#include< conio.h >
void main()
{
int clm[7][5],req[7][5],alloc[7][5],rsrc[5],avail[5],comp[7];
int first,p,r,i,j,prc,count,t;
clrscr();
count=0;
for(i=1;i<=7;i++)
comp[i]=0;
printf(Enter the no of processes:\n);
scanf(%d,&p);
printf(Enter the no of resources:\n);
scanf(%d,&r);
printf(Enter the claim for each process:);
for(i=1;i<=p;i++)
{
printf(\nFor process %d,i);
for(j=1;j<=r;j++)
{
scanf(%d,&clm[i][j]);
}
}
printf(Enter the allocation for each process:\n);
for(i=1;i<=p;i++)
{
printf(\nFor process ,i);
for(j=1;j<=r;j++)
{
scanf(%d,&alloc[i][j]);
}
}

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 71


Regulation-2013 Academic year-2015-16

printf(Enter total no of each resource:);


for(j=1;j<=r;j++)
scanf(%d,&rsrc[j]);
for(j=1;j<=r;j++)
{
int total=0;
avail[j]=0;
for(i=1;i<=p;i++)
{total+=alloc[i][j];}
avail[j]=rsrc[j]-total;
}
do
{
for(i=1;i<=p;i++)
{
for(j=1;j<=r;j++)
{
req[i][j]=clm[i][j]-alloc[i][j];
}
}
printf(\n\nAvailable resorces is:);
for(j=1;j<=r;j++)
{ printf( ,avail[j]); }
printf(\nClaim matrix:\t\tAllocation matrix:\n);
for(i=1;i<=p;i++)
{
for(j=1;j<=r;j++)
{
printf(%d,clm[i][j]);
}
printf(\t\t\t);
for(j=1;j<=r;j++)
{
printf(%d,alloc[i][j]);
}
printf(\n);
}
prc=0;
for(i=1;i<=p;i++)
{
if(comp[i]==0)//if not completed
{
prc=i;
for(j=1;j<=r;j++)
{
if(avail[j]

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 72


Regulation-2013 Academic year-2015-16

{
prc=0;
break;
}
}
}
if(prc!=0)
break;
}
if(prc!=0)
{
printf(\nProcess ,prc,runs to completion!);
count++;
for(j=1;j<=r;j++)
{
avail[j]+=alloc[prc][j];
alloc[prc][j]=0;
clm[prc][j]=0;
comp[prc]=1;
}
}
}
while(count!=p&&prc!=0);
if(count==p)
printf(\nThe system is in a safe state!!);
else
printf(\nThe system is in an unsafe state!!);
getch();
}

OUTPUT:
Enter the no of processes:
2

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 73


Regulation-2013 Academic year-2015-16

Enter the no of resources:


3
Enter the claim for each process:
For process I : 2 4 5
For process II: 2 5 3
Enter the total no of each resource : 5 5 2

Available resource is :

Claim matrix: allocation matrix:


245 123
253 234

The system is in an unsafe state!!

Result:
Thus the C program for Bankers Algorithm for Dead Lock Avoidance is executed and
verified successfully.

POST LAB QUESTIONS:


1) The wait-for graph is a deadlock detection algorithm that is applicable when :
a) all resources have a single instance

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 74


Regulation-2013 Academic year-2015-16

b) all resources have multiple instances


c) both a and b

2) An edge from process Pi to Pj in a wait for graph indicates that :


a) Pi is waiting for Pj to release a resource that Pi needs
b) Pj is waiting for Pi to release a resource that Pj needs
c) Pi is waiting for Pj to leave the system
d) Pj is waiting for Pi to leave the system

3) If the wait for graph contains a cycle :


a) then a deadlock does not exist
b) then a deadlock exists
c) then the system is in a safe state
d) either b or c

4) The Bankers algorithm is used


a) to prevent deadlock in operating systems
b) to detect deadlock in operating systems
c) to rectify a deadlocked state
d) none of the above

5) The disadvantage of invoking the detection algorithm for every request is :


a) overhead of the detection algorithm due to consumption of memory
b) excessive time consumed in the request to be allocated memory
c) considerable overhead in computation time
d) All of these

EXNO: 8 IMPLEMENTATION OF BANKERS ALGORITHM FOR DEAD LOCK


DETECTION

AU QUESTIONS:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 75


Regulation-2013 Academic year-2015-16

Write a C program to perform Deadlock detection using bankers algorithm

AIM:
To write a program to implement the Bankers Algorithm for Dead Lock detection.

PRE LAB-QUESTIONS:
1. Which of the following approaches do not require knowledge of the system state?
(A) deadlock detection. (B) deadlock prevention.
(C) deadlock avoidance. (D) none of the above.

2. A system is in a safe state only if there exists a ---------------------------


a) safe allocation
b) safe resource
c) safe sequence
d) All of these

3. An operating system contains 3 user processes each requiring 2 units of resource


R .The minimum number of units of R such that no deadlocks will ever arise is
(A) 4. (B) 3. (C) 5. (D) 6

4. To avoid deadlock
a) there must be a fixed number of resources to allocate
b) resource allocation must be done only once
c) all deadlocked processes must be aborted
d) inversion technique can be used

5. Which of the following approaches do not require knowledge of the system state?
(A) deadlock detection. (B) deadlock prevention.
(C) deadlock avoidance. (D) none of the above.

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. Request = Request vector for process Pi. If Request [i, j] = k, then process Pi wants k
instances of Rj.
9. If the new request comes then check that the system is in safety.
10. else if we allow the request.
11. Stop the program.

PROGRAM:
/Deadlock Detection algorithm implementation

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 76


Regulation-2013 Academic year-2015-16

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

void main()
{
int found,flag,l,p[4][5],tp,tr,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
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++)
{
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)
{

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 77


Regulation-2013 Academic year-2015-16

m[k]=i;
k++;
}
}
for(i=1;i<=tp;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{
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);
}
getch();
}
//program written by Mars. 27/11/2011. OS lab.

OUTPUT:

Enter total no. of processes : 4

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 78


Regulation-2013 Academic year-2015-16

Enter total no. of resources : 5


Enter claim (Max. Need) matrix :
01001
00101
00001
10101
Enter allocation matrix :
10110
11000
00010
00000
Enter resource vector (Total resources) :
21121
Enter availability vector (available resources) :
00001
deadlock causing processes are : 2 3

RESULT:

Thus the C program for Bankers Algorithm for Dead Lock Avoidance is executed and verified
successfully.
Post Lab Questions

1. Let S and Q be two semaphores initialized to 1, where P0 and P1 processes the following
statements

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 79


Regulation-2013 Academic year-2015-16

wait(S); wait(Q); signal(S);signal(Q) and


wait(Q); wait(S); signal(Q);signal(S); respectively.
The above situation depicts a _________ .

1 Semaphore 2 Deadlock 3 Signal 4 Interrupt

2) _________ is the situation in which a process is waiting on another process,which is also


waiting on another process ... which is waiting on the first process. None of the processes
involved in this circular wait are making progress.
1 Deadlock
2 Starvation
3 Dormant
4 None of the above

3) A set of resources' allocations such that the system can allocate resources to each process
in some order, and still avoid a deadlock is called ________.
1 Unsafe state
2 Safe state
3 Starvation
4 Greeedy allocation

4) In one of the deadlock prevention methods, impose a total ordering of all resource types,
and require that each process requests resources in an increasing order of enumeration.
This voilates the _______________ condition of deadlock
1 Mutual exclusion
2 Hold and Wait
3 Circular Wait
4 No Preemption

5) If the wait for graph contains a cycle :


a) then a deadlock does not exist
b) then a deadlock exists
c) then the system is in a safe state
d) either b or c

Ex No.9 PAGE REPLACEMENT ALGORITHMS


9a) IMPLEMENTATION OF FIFO PAGE REPLACEMENT ALGORITHM

AU QUESTION:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 80


Regulation-2013 Academic year-2015-16

Illustrate with a program how memory management is done using FIFO page replacement
algorithm

AIM:
To write a program to implement page replacement techniques by using FIFO.

PRE LAB QUESTION:

1) Which of the following page replacement algorithms suffers from Beladys Anomaly ?
a) Optimal replacement
b) LRU
c) FIFO
d) Both optimal replacement and FIFO

2) A process refers to 5 pages, A, B, C, D, E in the order : A, B, C, D, A, B, E, A, B, C, D, E.


If the page replacement algorithm is FIFO, the number of page transfers with an empty
internal store of 3 frames is :
a) 8
b) 10
c) 9
d) 7

3) In question 2, if the number of page frames is increased to 4, then the number of page
transfers :
a) decreases
b) increases
c) remains the same
d) None of these

4) A memory page containing a heavily used variable that was initialized very early and is
in constant use is removed, then the page replacement algorithm used is :
a) LRU
b) LFU
c) FIFO
d) None of these

5) A FIFO replacement algorithm associates with each page the _______


a) time it was brought into memory
b) size of the page in memory
c) page after and before it
d) All of these

ALGORITHM:

1. Get length of the reference string, say l.


2. Get reference string and store it in an array, say rs.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 81


Regulation-2013 Academic year-2015-16

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);
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]);
}
}

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 82


Regulation-2013 Academic year-2015-16

printf("\n\nTotal no. of page faults : %d\n",count);


}

OUTPUT:

$ gcc fifopr.c
$ ./a.out
Enter length of ref. string : 20
Enter reference string :
12342156212376321236
Enter number of frames : 5
Ref. str Pageframes
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 2345
6 6 2345
2
1 6 1345
2 6 1245
3 6 1235
7 6 1237
6
3
2
1
2
3
6
Total no. of page faults : 10

Result:

Thus the C program for page replacement for FIFO is executed and verified successfully.

EX:NO:9b IMPLEMENTATION OF LRU PAGE REPLACEMENT ALGORITHM

AU QUESTION:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 83


Regulation-2013 Academic year-2015-16

Illustrate with a program how memory management is done using LRU page replacement
algorithm.

Aim:
To write a program to implement page replacement techniques by using LRU.

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:
#include <stdio.h>
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]);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 84


Regulation-2013 Academic year-2015-16

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;
count++;
}
for(k=0; k<nf; k++)
printf("%4d", frame[k]);
}
}
printf("\n\nTotal no. of page faults : %d\n", count);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 85


Regulation-2013 Academic year-2015-16

}
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:
$ gcc lrupr.c
$ ./a.out
Length of Reference string : 20

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 86


Regulation-2013 Academic year-2015-16

Enter reference string :


12342156212376321236
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 12345
6 12645
2
1
2
3 12635
7 12637
6
3
2
1
2
3
6
Total no. of page faults : 8

Result:

Thus the C program for page replacement for LRU is executed and verified successfully.

EX:NO:9c IMPLEMENTATION OF LFU PAGE REPLACEMENT ALGORITHM

AU QUESTION:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 87


Regulation-2013 Academic year-2015-16

Illustrate with a program how memory management is done using LFU page replacement
algorithm.

AIM:

To write a program to implement page replacement techniques by using LFU.

ALGORITHM:

1.Start Program
2.Read Number Of Pages And Frames
3.Read Each Page Value
4.Search For Page In The Frames
5.If Not Available Allocate Free Frame
6.If No Frames Is Free Repalce The Page With The Page That Is Leastly Used
7.Print Page Number Of Page Faults
8.Stop process.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#define max 25

void main()
{
int frame[10],length[10],index,highest;
int i,j,k,nf,np=0,page[max],temp;
int flag=0,pf=0,found=0;
clrscr();
printf("Enter no. of Frames:");
scanf("%d",&nf);
for(i=0;i<nf;i++)
frame[i]=-1;
printf("Enter pages (press -999 to exit):\n");
for(i=0;i<max;i++)
{
scanf("%d",&temp);
if(temp==-999) break;
page[i]=temp;
np++;
}
for(i=0;i<np;i++)
{
flag=0;
for(j=0;j<nf;j++)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 88


Regulation-2013 Academic year-2015-16

{
if(frame[j]==page[i])
{
printf("\n\t");
flag=1;break;
}
}
if(flag==0)
{
for(j=0;j<nf;j++)
{
for(temp=i+1;temp<np;temp++)
{
length[j]=0;
if (frame[j]==page[temp])
{length[j]=temp-i;break;}
}
}
found=0;
for(j=0;j<nf;j++)
{
if(length[j]==0)
{
index=j;
found=1;
break;
}
}
if(found==0)
{
highest=length[0];
index=0;
for(j=1;j<nf;j++)
{
if(highest<length[j])
{
highest=length[j];
index=j;
}
}
}
frame[index]=page[i];
printf("\nPage fault: ");
pf++;
}
for(k=0;k<nf;k++)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 89


Regulation-2013 Academic year-2015-16

printf("%d\t",frame[k]);
}
printf("\nNumber of page faults is: %d ",pf);
getch();
}

OUTPUT
Enter number of frames:3
Enter pages (press -999 to exit):
7
0
1
2
0
3
0
4
2
3
0
3
2
1
2
0
1
7
0
1
-999

Page fault: 7 -1 -1
Page fault: 7 0 -1
Page fault: 7 0 1
Page fault: 2 0 1
2 0 1
Page fault: 2 0 3
2 0 3
Page fault: 2 4 3
2 4 3
2 4 3
Page fault: 2 0 3
2 0 3
2 0 3
Page fault: 2 0 1
2 0 1

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 90


Regulation-2013 Academic year-2015-16

2 0 1
2 0 1
Page fault: 7 0 1
7 0 1
7 0 1
Number of page fault is 9

Result:

Thus the C program for page replacement for LFU is executed and verified successfully.

POST LAB QUESTION:


1) When using counters to implement LRU, we replace the page with the :
a) smallest time value

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 91


Regulation-2013 Academic year-2015-16

b) largest time value


c) greatest size
d) None of the mentioned

2) In the stack implementation of the LRU algorithm, a stack can be maintained in a


manner :
a) whenever a page is used, it is removed from the stack and put on top
b) the bottom of the stack is the LRU page
c) the top of the stack contains the LRU page and all new pages are added to the top
d) None of the mentioned

3) The operating system maintains a ______ table that keeps track of how many frames
have been allocated, how many are there, and how many are available.
a) page
b) frame
c) mapping
d) memory

4) Applying the LRU page replacement to the following reference string :


12452124
The main memory can accommodate 3 pages and it already has pages 1 and 2. Page 1 came
in before page 2.
How many page faults will occur ?
a) 2
b) 3
c) 4
d) 5

5) Increasing the RAM of a computer typically improves performance because:


a) Virtual memory increases
b) Larger RAMs are faster
c) Fewer page faults occur
d) None of the mentioned

EX:10 IPC USING SHARED MEMORY

AU QUESTION:

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 92


Regulation-2013 Academic year-2015-16

Develop an application and demonstrate how Message queue is used in Inter process
communication

AIM:
To write a program to implement IPC using shared memory.

PRE LAB QUESTIONS:


1) Inter process communication :
a) allows processes to communicate and synchronize their actions when using the same address
space.
b) allows processes to communicate and synchronize their actions without using the same
address space.
c) allows the processes to only synchronize their actions without communication.
d) None of these

2) Message passing system allows processes to :


a) communicate with one another without resorting to shared data.
b) communicate with one another by resorting to shared data.
c) share data
d) name the recipient or sender of the message

3) An IPC facility provides atleast two operations : (choose two)


a) write message
b) delete message
c) send message
d) receive message

4) Messages sent by a process :


a) have to be of a fixed size
b) have to be a variable size
c) can be fixed or variable sized
d) None of these

5) The link between two processes P and Q to send and receive messages is called :
a) communication link
b) message-passing link
c) synchronization link
d) All of these

ALGORITHM:
Server
1. Initialize size of shared memory shmsize to 27.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 93


Regulation-2013 Academic year-2015-16

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 az 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

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);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 94


Regulation-2013 Academic year-2015-16

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()
{
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);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 95


Regulation-2013 Academic year-2015-16

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 the program to develop application like Inter process Communication using shared memory
and pipes is implemented successfully.

POST LAB QUESTIONS:

1) Which of the following are TRUE for direct communication (choose two)

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 96


Regulation-2013 Academic year-2015-16

a) A communication link can be associated with N number of process(N = max. number of


processes supported by system)
b) A communication link can be associated with exactly two processes
c) Exactly N/2 links exist between each pair of processes(N = max. number of processes
supported by system)
d) Exactly one link exists between each pair of processes

2) In indirect communication between processes P and Q :


a) there is another process R to handle and pass on the messages between P and Q
b) there is another machine between the two processes to help communication
c) there is a mailbox to help communication between P and Q
d) None of these

3) In the non blocking send :


a) the sending process keeps sending until the message is received
b) the sending process sends the message and resumes operation
c) the sending process keeps sending until it receives a message
d) None of these

4) In the Zero capacity queue : (choose two)


a) the queue has zero capacity
b) the sender blocks until the receiver receives the message
c) the sender keeps sending and the messages dont wait in the queue
d) the queue can store atleast one message

5) The Zero Capacity queue :


a) is referred to as a message system with buffering
b) is referred to as a message system with no buffering
c) is referred to as a link
d) None of these

6) Bounded capacity and Unbounded capacity queues are referred to as :


a) Programmed buffering
b) Automatic buffering
c) User defined buffering
d) No buffering

Ex.No11IMPLEMENT PAGING TECHNIQUE OF MEMORY MANAGEMENT-


FIXED PARTITION

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 97


Regulation-2013 Academic year-2015-16

AU QUESTION:
Develop a program to implement paging technique with fixed partition memory
management technique

AIM:

To implement Fixed Partition Memory Management Scheme.

PRE LAB QUESTIONS:


1) In internal fragmentation, memory is internal to a partition and :
a) is being used
b) is not being used
c) is always used
d) None of these

2) A solution to the problem of external fragmentation is :


a) compaction
b) larger memory space
c) smaller memory space
d) None of these

3) Another solution to the problem of external fragmentation problem is to :


a) permit the logical address space of a process to be noncontiguous
b) permit smaller processes to be allocated memory at last
c) permit larger processes to be allocated memory at last
d) All of these

4) If relocation is static and is done at assembly or load time, compaction _________.


a) cannot be done
b) must be done
c) must not be done
d) can be done

5) The disadvantage of moving all process to one end of memory and all holes to the other
direction, producing one large hole of available memory is :
a) the cost incurred
b) the memory used
c) the CPU used
d) All of these

ALGORITHM:

1. Get the number of pages and their sizes.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 98


Regulation-2013 Academic year-2015-16

2. Create pages with corresponding sizes using linked list as free nodes.
3. Get the number of programs <= number of pages to be allocated and their sizes.
4. Start with the first page, if the first program size fits with this page then allocate first page
for the first program. Otherwise check with next program and so on.
5. Continue the process with next pages.
6. Maintain the allotted pages as a separate linked list.
7. Calculate internal fragmentation balance spaces in each page and
external fragmentation sizes of unallocated pages.
8. Display the starting and ending address of Free nodes and allotted nodes and also the
internal and external fragmentations.

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct node
{
int size;
int busy;
int pid;
struct node *start, *end, *next;
};
struct node *freenode=NULL, *allotnode=NULL, *newnode, *temp1=NULL, *temp2=NULL,
*anode;
int internal=0, external=0;
int no_of_pages, size[20], allot[10]={0};
int no,np,x,y,t=0;
void partition();
void allocate();
void display();
void main()
{
int ch;
clrscr();

while(1)
{
printf("\n \nEnter the choice: \n 1.Partition \n 2.Allocate \n 3.Display \n 4.Exit \n");
scanf("%d",&ch);
switch(ch)
{
case 1:
partition();
break;
case 2:
allocate();

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 99


Regulation-2013 Academic year-2015-16

break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Wrong Choice");
break;
}
}
}
void partition()
{
int addr;
printf("\nEnter the no of pages\n");
scanf("%d",&no_of_pages);
printf("\nEnter the page sizes in Bytes\n ");
for(no=0;no<no_of_pages;no++)
{
scanf("%d",&size[no]);
addr=(int *)malloc(size[no]);
newnode=(struct node *)malloc(sizeof(struct node));
newnode->start=addr;
newnode->end=addr+size[no];
newnode->size=size[no];
newnode->busy=0;
newnode->pid=0;
newnode->next=NULL;
if(freenode==NULL)
freenode=newnode;
else
{
temp1=freenode;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=newnode;
}
}
}
void allocate()
{
int no_of_prog, sizep[20];
anode=(struct node *)malloc(sizeof(struct node));
do

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 100


Regulation-2013 Academic year-2015-16

{
printf("\nEnter the number of programs<= %d\n",no_of_pages);
scanf("%d",&no_of_prog);
}
while(no_of_prog > no_of_pages);
printf("\nEnter the program sizes in Bytes\n");
for(np=0;np<no_of_prog;np++)
scanf("%d",&sizep[np]);
//Program to allocate the pages to the programs using firstfit
temp1=freenode;
while(temp1 != NULL)
{
for(y=0;y<no_of_prog;y++)
{
if(temp1->size>=sizep[y] && temp1->busy==0 && allot[y]==0)
{
temp1->busy=1;
allot[y]=1;
anode->pid=y+1;
anode->busy=1;
anode->size=temp1->size;
anode->start=temp1->start;
t=(int)temp1->start;
anode->end=t+sizep[y]-1;
anode->next=NULL;
internal+=temp1->size-sizep[y];
if(allotnode==NULL)
allotnode=anode;
else
{
temp2=allotnode;
while(temp2->next!=NULL)
temp2=temp2->next;
temp2->next=anode;
}
}
}
printf("Proces id %d \n",allotnode->pid);
printf("Start addr %u \n",allotnode->start);
printf("End addr %u \n\n",allotnode->end);
if(temp1->busy==0)
external+=temp1->size;
temp1=temp1->next;
}
printf("Internal Fragmentation = %d\n",internal);
printf("External Fragmentation = %d\n",external);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 101


Regulation-2013 Academic year-2015-16

}
void display()
{
temp1=freenode;
printf("\n\nFree nodes are\n\n\n");
while(temp1!=NULL)
{
if((temp1->busy)==0)
{
printf("Start addr %u \n",temp1->start);
printf("End addr %u \n",temp1->end);
printf("Size %d \n",temp1->size);
}
temp1=temp1->next;
}
}

Output:
Enter the choice:
1.Partition
2.Allocate
3.Display
4.Exit
1
Enter the no of pages
3
Enter the page sizes in Bytes
20
40
60
Enter the choice:
1.Partition
2.Allocate
3.Display
4.Exit
3
Free nodes are
Start addr 2310
Endaddr 2330
Size 20
Start addr 2350
Endaddr 2390
Size 40
Start addr 2410
Endaddr 2470

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 102


Regulation-2013 Academic year-2015-16

Size 60
Enter the choice:
1.Partition
2.Allocate
3.Display
4.Exit
2
Enter the number of programs<= 3
3
Enter the program sizes in Bytes
15
30
70
Proces id 1
Start addr 2310
End addr 2324
Proces id 2
Start addr 2350
End addr 2379
Proces id 2
Start addr 2350
End addr 2379
Internal Fragmentation = 15
External Fragmentation = 60
Enter the choice:
1.Partition
2.Allocate
3.Display
4.Exit

RESULT:

Thus the program called Fixed Partition Memory Management Scheme is implemented
successfully.

POST LAB QUESTIONS:


1) __________ is generally faster than _________ and _________.

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 103


Regulation-2013 Academic year-2015-16

a) first fit, best fit, worst fit


b) best fit, first fit, worst fit
c) worst fit, best fit, first fit
d) None of these

2) External fragmentation exists when :


a) enough total memory exists to satisfy a request but it is not contiguous
b) the total memory is insufficient to satisfy a request
c) a request cannot be satisfied even when the total memory is free
d) None of these

3) External fragmentation will not occur when :


a) first fit is used
b) best fit is used
c) worst fit is used
d) no matter which algorithm is used, it will always occur

4) Which of the following statements is false?


a) the technique of storage compaction involves moving all occupied areas of storage to one end
or other of main storage
b) compaction does not involve relocation of programs
c) compaction is also know as garbage collection
d) the system must stop everything while it performs the compaction

5) When the memory allocated to a process is slightly larger than the process, then :
a) internal fragmentation occurs
b) external fragmentation occurs
c) both a and b
d) neither a nor b

EX No :12. IMPLEMENTATION OF THREADING & SYNCHRONIZATION


APPLICATIONS

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 104


Regulation-2013 Academic year-2015-16

AU QUESTION:
Develop a program to implement threading and illustrate how applications are performed
with synchronization process

AIM:
To implement threading & synchronization applications.

PRE LAB QUESTION:


1. Which one of the following is not shared by threads?
a) program counter
b) stack
c) both (a) and (b)
d) none of the mentioned

2. A process can be
a) single threaded
b) multithreaded
c) both (a) and (b)
d) none of the mentioned

3. If one thread opens a file with read privileges then


a) other threads in the another process can also read from that file
b) other threads in the same process can also read from that file
c) any other thread can not read from that file
d) all of the mentioned

4. The time required to create a new thread in an existing process is


a) greater than the time required to create a new process
b) less than the time required to create a new process
c) equal to the time required to create a new process
d) none of the mentioned

5. When the event for which a thread is blocked occurs,


a) thread moves to the ready queue
b) thread remains blocked
c) thread completes
d) a new thread is provided

ALOGRITHM:

1. Start the program


2. Declare variables.
3. Read the process no and process size.
4. Code on threads - creating, detaching, joining, etc. They also include functions to
set/query thread attributes (joinable, scheduling etc.)
5. Routines that deal with synchronization, called a "mutex",

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 105


Regulation-2013 Academic year-2015-16

6. Condition variables that address communications between threads that share a mutex.
7. Print the results
8. Stop the process.
9. End.

PROGRAM:

//Threading without synchronization

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

pthread_t tid[2];
int counter;

void* doSomeThing(void *arg)


{
unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);

for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);

return NULL;
}

int main(void)
{
int i = 0;
int err;

while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));

i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 106


Regulation-2013 Academic year-2015-16

return 0;
}

Output:

$ ./tgsthreads
Job 1 started
Job 2 started
Job 2 finished
Job 2 finished

//Threading with synchronization

#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* doSomeThing(void *arg)


{
pthread_mutex_lock(&lock);

unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);

for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void)
{
int i = 0;
int err;

if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 107


Regulation-2013 Academic year-2015-16

while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);

return 0;
}

Output:
$ ./threads
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished

Result:

Thus the C program for thread and synchronization is executed and verified successfully.
POST LAB QUESTIONS:
1. The jacketing technique is used to
a) convert a blocking system call into nonblocking system call

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 108


Regulation-2013 Academic year-2015-16

b) create a new thread


c) communicate between threads
d) terminate a thread

2. Termination of the process terminates


a) first thread of the process
b) first two threads of the process
c) all threads within the process
d) no thread within the process

3. Which one of the following is not a valid state of a thread?


a) running
b) parsing
c) ready
d) blocked

4. The register context and stacks of a thread are deallocated when the thread
a) terminates
b) blocks
c) unblocks
d) spawns

5. Thread synchronization is required because


a) all threads of a process share the same address space
b) all threads of a process share the same global variables
c) all threads of a process can share the same files
d) all of the mentioned

IFETCE/IT/II Yr/IV Sem/IT6412/OS/LAB MANUAL/VER 1.1 109

Anda mungkin juga menyukai