0% found this document useful (0 votes)
50 views71 pages

R.M.K. Engineering College: Department of Computer Science and Engineering

Uploaded by

Harish Kumar R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views71 pages

R.M.K. Engineering College: Department of Computer Science and Engineering

Uploaded by

Harish Kumar R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

R.M.K.

ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

20CS412
OPERATING SYSTEMS

LAB MANUAL
R2020

2022-23 EVEN SEMESTER

B.E. COMPUTER SCIENCE AND ENGINEERING

Prepared by Approved by Approved by

Dr.B.Jaison, Professor /CSE Dr.T. Sethukarasi Dr. K. A. Mohamed Junaid

Mr.G.Thanigaivel, AP/CSE Professor & Head / CSE Principal

Ms.P.Ilampiray, AP/CSE
R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Vision
To evolve as a Centre of Academic Excellence and Advanced Research in the field of Computer Science and
Engineering and develop professionals who can meet with the societal issues.
Mission
M1: To provide a good environment with latest technological infrastructure facilities, teaching-learning
ambience and interaction with industry in the area of Computer Science and Engineering.
M2: To develop graduates of world class technical competence, entrepreneurial skill and to encourage for
higher education in the area of Computer Science and Engineering, with necessary skills to solve real world
problems.
M3:To inculcate graduates with high social responsibility, right attitude, discipline and an inclination towards
offering their professional expertise in serving the society.
Programme Educational Objectives
PEO 1. Apply the principles and practices of Computer Science and Engineering encompassing Mathematics,
Science and Basic Engineering and to employ the modern engineering tools effectively in their profession with
their world class technical competence.
PEO 2. Possess expertise to function as members of multi-disciplinary teams and implement software
technology solutions for real world problems of international standards and will be achievers at global level.
PEO 3. Excel in the field of software industry or in higher studies endowed with the spirit of innovation and
entrepreneurship by evolving their professional knowledge on a lifelong basis.
PEO 4. Practice the profession with ethics, integrity, leadership and social responsibility with a good insight of
the changing societal needs for the benefit of humanity.
Program Specific Outcome
PSO 1: Apply knowledge acquired from the basic hardware design and software core areas of Computer Science
and Engineering for solving real world problems.
PSO 2: Apply cutting edge technologies and strong analytical skills to develop quality software in scientific
and business applications for the betterment of society and Industry.
PSO 3: Employ modern computer languages, environments and platforms in creating innovative career paths
to be an entrepreneur and with a zeal for higher studies.
R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Syllabus
20CS412 OPERATING SYSTEMS LABORATORY L T P C

OBJECTIVES: 0 0 4 2

 To practice system calls and shell programming

 To implement various CPU scheduling algorithms

 To build inter-process communication deadlock detection and avoidance algorithms.

 To design page replacement and disk scheduling algorithms

 To implement file allocation strategies

LIST OF EXERCISES:

1. Basic Unix file system commands such as ls, cd, mkdir, rmdir, cp, rm, mv, more, lpr, man, grep, sed,
etc.

2. Shell Programming

3. Programs for Unix System Calls. a. Write a program to fetch the below information; Name of the
operating system, Current release level, Current version level, Total usable main memory size,
Available memory size, Amount of shared memory, Memory used by buffers, Total swap space size,
and Swap space still available.
a) Use system calls to imitate the action of UNIX command "ls"
b) Use system calls to imitate the action of UNIX command "grec"
c) Implement process life cycle: Use the system calls fork(), exec(), wait(), waitpid(), exit(0), abort()
and kill().

4. Write a program to implement the following actions using pthreads


a) Create a thread in a program and called Parent thread, this parent thread creates another thread (Child
thread) to print out the numbers from 1 to 20. The Parent thread waits till the child thread finishes

5. Process Synchronization using Semaphores. A shared data has to be accessed by two categories of
processes namely A and B. Satisfy the following constraints to access the data without any data loss.
i. When a process A1 is accessing the database another process of the same category is permitted.
ii. When a process B1 is accessing the database neither process A1 nor another process B2 is
permitted.
iii. When a process A1 is accessing the database process B1 should not be allowed to access the
database. Write appropriate code for both A and B satisfying all the above constraints using
semaphores.
Note: The time-stamp for accessing is approximately 10 sec.

6. Implementation of IPC using Shared memory a. Write a UNIX system call program to implement the
following shared memory concept
i. In process 1 - Creation a shared memory of size 5 bytes with read/write permission and enter
balance amount of Rs 1000.
ii. In process 2 – Add Rs. 200 to your balance. During this modification maintain the atomicity of
shared memory using binary semaphore
iii. In process 3 – Subtract Rs. 800 to your balance. During this also modification maintain the
atomicity of shared memory using binary semaphore
iv. In process 4 – Display the current balance of shared memory
v. Delete the shared memory

7. Implementation of IPC using message queue


i. Get the input data (integer value) from a process called sender
ii. Use Message Queue to transfer this data from sender to receiver process
iii. The receiver does the prime number checking on the received data
iv. Communicate the verified/status result from receiver to sender process,
This status should be displayed in the Sender process. Note: Simultaneously execute two or
more processes. Don’t do it as a single process.

8. Write C programs to implement the various CPU Scheduling Algorithms.

9. Bankers Algorithm for Deadlock Avoidance

10. Implementation of Memory Allocation Methods for fixed partition

11. Implementation of Paging Technique of Memory Management

12. Implementation of Page Replacement Algorithms

13. Implementation of disk scheduling

14. Implementation of File Allocation Strategies

COURSE OUTCOMES

At the end of this course, the students will be able to:

CO1: Practice system calls and shell programming


CO2: Implement various CPU scheduling algorithms
CO3: Build inter process communication deadlock detection and avoidance algorithms.
CO4: Design page replacement and disk scheduling algorithms
CO5: Implement file allocation strategies
Page Date
Ex. No. List of Exercises
No.
1 Basics of UNIX commands 8 21/1/23
Shell Programming- Area and circumference of a 28/1/23
A circle 27

Swapping two numbers 28/1/23


B 27

Calculate gross salary 28/1/23


C 28

Greatest of two numbers 28/1/23


D 29

Check odd or even 28/1/23


E 29

Check positive, negative or zero 28/1/23


F 30
2 28/1/23
G Basic arithmetic operations 30

Sum of first five natural number 28/1/23


H 32

Sum of odd numbers up to n 28/1/23


I 33

Sum of even numbers upto n 28/1/23


J 34

Factorial of a given number 28/1/23


K 35
28/1/23
L Check armstrong number or not 36

4/2/23
UNIX system calls 37

A Imitate the action of “ls” command 37 4/2/23


3
4/2/23
B Imitate the action of “grep” command 40
4/2/23
C Implement process life cycle 41
11/2/23
4 Implement p- threads and synchronization 43

18/2/23
5 Implement semaphores 47

18/2/23
6 Implement IPC using shared memory 50

25/2/23
7 Implement IPC using message queue 51

Scheduling algorithms 52 11/3/23


11/3/23
A First come first served scheduling algorithm 52
11/3/23
8 B SJF scheduling algorithm 55

C Priority scheduling 57 11/3/23


11/3/23
D Round robin scheduling 60
Implement Banker’s algorithm for deadlock 18/3/23
9 62
avoidance
Implementing memory management schemes 25/3/23
67

First Fit 25/3/23


A 67
10
Best Fit 25/3/23
B 72

Worst Fit 25/3/23


C 77
Implement paging technique for memory 1/4/23
11 81
management
Implement page replacement algorithms 8/4/23
83

FIFO 8/4/23
12 A 83

LRU 8/4/23
B 85

Implement Disk scheduling 8/4/23


13 90

Implement file organization techniques 29/4/23


92

Single level directory 29/4/23


A 92
14
Two level directory 29/4/23
B 93

Hierarchical 29/4/23
C 95
Exp. No.: 1 BASIC UNIX COMMANDS

AIM:
To study the basic UNIX commands and their syntax.

COMMANDS:
Command is a Series of characters that invokes the shell and tells the Unix operating system to
perform some operations.

CLASSIFICATION OF COMMANDS:
1. General Purpose Commands
2. Directory Commands
3. File Commands
4. Pattern Searching Commands
5. File Permission Commands

GENERAL PURPOSE COMMANDS:

1. COMMAND : date
PURPOSE : To display the current date and time
SYNTAX : $date
EXAMPLE : $date
OUTPUT : Thu Nov 15 16:24:10 IST 2007

2. COMMAND : cal
PURPOSE : To display the calendar
SYNTAX : $cal
EXAMPLE : $cal 1 2008
OUTPUT :
January 2008
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

NOTE : Without any argument ‘cal’ displays the current, previous and
next month calendar along with date and time.

3.COMMAND : echo
PURPOSE : To display the message on the screen.
SYNTAX : $echo
EXAMPLE : $echo COMPUTER SCIENCE
OUTPUT : COMPUTER SCIENCE
4. COMMAND : who
PURPOSE : To show the users currently logged on.
SYNTAX : $who
EXAMPLE : $who
OUTPUT : root :0 Nov 15 15:00
root pts/1 Nov 15 15:01 (:0.0)
student pts/1 Nov 15 15:09 (ws205)

5. COMMAND : whoami
PURPOSE : To know in which terminal the user is currently logged on
SYNTAX : $whoami
EXAMPLE : $whoami
OUTPUT : student

6. COMMAND : tty
PURPOSE : To report the name of the device the user is currently using for
a terminal
SYNTAX: $tty
EXAMPLE : $tty
OUTPUT : /dev/pts/3

7. COMMAND : df
PURPOSE : To show disk usage
SYNTAX : $df
EXAMPLE : $df
OUTPUT : Filesystem 1K-blocks Used Available Use%
Mounted on
/dev/mapper/VolGroup00-LogVol00
38059528 4901880 31224336 14% /
/dev/hdc1 101086 8967 86900 10% /boot
none 62664 0 62664 0% /dev/shm

8. COMMAND : man
: Gives online help to all commands followed by additional
PURPOSE information
SYNTAX : $ man <command>
EXAMPLE : $man ls
OUTPUT :
LS(1) User Commands LS(1)
NAME

ls - list directory contents


SYNOPSIS

ls [OPTION]... [FILE]...
DESCRIPTION

List information about the FILEs (the current directory by


default).
Sort entries alphabetically if none of -cftuSUX nor --sort.

…….

9. COMMAND : history
PURPOSE : To print the recently used commands
SYNTAX : $history
EXAMPLE : $history 5
1119
1120
1121
1122
1123

10. COMMAND : clear


PURPOSE : To clear the screen
SYNTAX : $clear
EXAMPLE : $clear

DIRECTORY COMMANDS:
1. COMMAND : pwd
PURPOSE : To display the pathname of the current working directory
SYNTAX : $pwd
EXAMPLE : $pwd
OUTPUT : /home/student

2. COMMAND : mkdir
PURPOSE : To create a new Directory
SYNTAX : $mkdir <directory name>
EXAMPLE : $mkdir Oslab
OUTPUT :$
3. COMMAND : cd
: To change from one directory (working) to another directory
PURPOSE specified by its arguments
SYNTAX : $ cd <directory name>
EXAMPLE : $ cd Oslab
OUTPUT : Oslab]$
NOTE : Without any argument, ‘cd’ changes to the home directory
4. COMMAND : rmdir
PURPOSE : To remove the existing directory
SYNTAX : $rmdir <directory name>
EXAMPLE : $rmdir Oslab
OUTPUT :$
5. COMMAND : ls
PURPOSE : To list out the names of all files in the current working
directory
SYNTAX : $ls
EXAMPLE : $ls
OUTPUT : asha joy keerthi
FILE COMMANDS:
1. COMMAND : cat
a) PURPOSE : To create a new file
SYNTAX : $cat > <filename>
EXAMPLE : $cat > sample
UNIX <ctrl+D>

OUTPUT :$
b) PURPOSE : To append the file contents

SYNTAX : $cat >> <filename>


EXAMPLE : $cat sample
Linux <ctrl+D>

OUTPUT :$
c) PURPOSE : To display the file contents

SYNTAX : $cat <filename>


EXAMPLE : $cat sample
OUTPUT : UNIX.
Linux

d) PURPOSE : To concatenate the multiple files into a single file

SYNTAX : $cat <file1> <file2> >> <file3>


EXAMPLE : $cat sample sample1 >> sample3
OUTPUT : $
2. COMMAND : sort

PURPOSE : To sort the file contents in some particular order


SYNTAX : $sort <filename>
EXAMPLE : $sort sample
OUTPUT : Linux

UNIX
3. COMMAND : cp
PURPOSE : To copy a file to another file.
SYNTAX : $cp <source file> <destination file>
EXAMPLE : $cp sample sam
OUTPUT :$
NOTE : Using ‘cp’ , we can copy file(s) to a directory and also copy a
directory to another directory.

4. COMMAND : mv
PURPOSE : To move the contents of file to another (that is, rename a file)
SYNTAX : $mv <source file> <destination file>
EXAMPLE : $ mv sam sam1
OUTPUT :$
NOTE : Using ‘mv’, we can move file(s) to a directory and also move
a directory to another directory (that is, rename a directory).

5. COMMAND : rm
PURPOSE : To delete a file permanently
SYNTAX : $rm <filename>
EXAMPLE : $rm sam1
OUTPUT :$

6. COMMAND : file
PURPOSE : To find the type of file present in that particular directory
SYNTAX : $file <filename>
EXAMPLE : $file sample1
OUTPUT :ASCII text
NOTE : To find the type of all files in a directory, can use the syntax,
$file <directory name> / *
7. COMMAND : wc
PURPOSE : To count the number of lines, words and characters in a file
SYNTAX : $wc <filename>
EXAMPLE : $wc sample
OUTPUT : 2 2 10 sample
8. COMMAND : lp
PURPOSE : To print the contents of a file to the printer
SYNTAX : $lp <filename>
EXAMPLE : $lp sample
OUTPUT :$
PATTERN SEARCHING COMMANDS:

These commands are used to search for a particular pattern in one or more files
and display the result on the Standard Output.

1. COMMAND : grep (global search for regular expression and print)

PURPOSE : To search and display a line for a given word or given pattern

SYNTAX : $grep <pattern> <filename>


EXAMPLE : $grep i sample
OUTPUT : Linux

NOTE : egrep ( extended version of grep) and grep (fast grep) are the

other pattern searching commands.


FILE PERMISSION COMMANDS:

Different modes or permissions associated with the file and directory in the
UNIX are :
(i) Owner Permissions
(ii) Group Permission
(iii) Other Permissions

The actions that can be performed on a file or a directory by Owner, group or


others are read(4), write(2) and execute(1) permissions.
1. COMMAND : chmod
PURPOSE : To change the access permissions for the owner, group and
others.
SYNTAX : $chmod <mode > <filename>
EXAMPLE : $chmod 754 sample
OUTPUT :$

2. COMMAND : chown
PURPOSE : To change the ownership of a file
SYNTAX : $chown <owner> <filename>
EXAMPLE : $chown directory sample
OUTPUT :$

RESULT:
Thus the basic UNIX commands were studied successfully.
Ex. No. : 2
Shell Programming
Date:

Exercise Number : 2.a


Title: Area and Circumference of Circle

Aim:
To write a shell program for finding the area and circumference of the circle.

Algorithm:

Step 1: Start the process.


Step 2: Read the radius r.
Step 3: Calculate area of the circle using the formula, area= Π*r*r
Step 4: Calculate circumference of the circle using the formula circumference= 2*Π*r
Step 5: Print area and circumference of the circle.
Step 6: Stop the process.

Program:

#shell program to calculate the area and circumference of the circle


echo enter the radius
read r
area=`expr 22 / 7 \* $r \* $r`
circumference=`expr 2 \* 22 / 7 \* $r`
echo area= $area
echo circumference= $circumference

Output:
algin@ubuntu:~/shell$ sh circle.sh enter the radius
3
area= 27
circumference= 18

Result:

Thus, the shell program for finding the area and circumference of the circle has been executed and verified.
Date :
Exercise Number : 2.b
Title: Swapping two numbers

Aim:
To write a shell program to swap two numbers using a temporary variable.

Algorithm:
Step 1: Start the process.
Step 2: Read two variables 'a' and 'b'.
Step 3: Print the values of the variable before swapping.
Step 4: Assign 'a' value to temporary variable 'c', 'b' value to 'a' and 'c' value to 'b'.
Step 5: Print the values after swapping.
Step 6: Stop the process.
Program:
#shell program to swap two numbers using a temporary variable

echo "enter the two numbers for swapping"


read a b
echo Before swapping echo A=$a and B=$b
c=$a
a=$b
b=$c
echo After swapping echo A=$a and B=$b

Output:
algin@ubuntu:~/shell$ sh swap.sh enter the two numbers for swapping 23 45
Before swapping A=23 and B=45
After swapping A=45 and B=23

Result :
Thus, the shell program to swap two numbers using a temporary variable has been executed and verified
Date :
Exercise Number : 2.c
Title: Calculate the gross salary

Aim:
To write a Shell program to find the gross salary.

Algorithm:
Step 1: Start the process.
Step 2: Read name and salary of the employee.
Step 3: Calculate da=s*47/100. Step 4: Calculate hra=s*12/100. Step 5: Calculate cca=s*3/100.
Step 6: Calculate gross=s+hra+cca+da.
Step 7: Print gross salary of the employee.

Program:
#shell program to find the gross salary echo Enter the employee name
read name
echo enter the basic salary read s
da=`expr $s \* 47 / 100` hra=`expr $s \* 12 / 100` cca=`expr $s \* 3 / 100`
gross=`expr $s + $hra + $cca + $da` echo The gross salary of $name is $gross

Output:
algin@ubuntu:~/shell$ sh gross.sh Enter the employee name
Algin
enter the basic salary 12413
The gross salary of Algin is 20108

Result:
Thus, the Shell program to find the gross salary has been executed and verified.
Date :
Exercise Number : 2.d
Title: Greatest of two numbers

Aim:
To write a Shell program to find the greatest of two numbers.

Algorithm:
Step 1: Start the process.
Step 2: Read two variables 'a' and 'b'.
Step 3: Assign 'a' value to big.
Step 4: Check if(b>big) then assign 'b' value to big and print “big is the greatest”.
Step 5: Stop the process.

Program:
#shell script to find the greatest of two numbers

echo Enter the two numbers


read a b
big=$a
if [ $b -gt $big ]
then
big=$b
fi
echo $big is the greatest

Output:
algin@ubuntu:~/shell$ sh grea_2no.sh Enter the two numbers
21 79
79 is the greatest

Result:
Thus, the shell program to find the greatest of two numbers has been executed and verified.
Date :
Exercise Number : 2.e
Title: Check add or even

Aim:
To write a Shell program to check whether a given number is odd or even.
Algorithm:
Step 1: Start the process.
Step 2: Read the input value n.
Step 3: Find n %2 and store the result in r.
Step 4: Check if r=0 then print “The given no is even” else print “The given no is odd”.
Step 5: Stop the process.

Program:
#shell program to check whether a given number is odd or even
echo Enter a number
read n
r=`expr $n % 2`
if [ $r -eq 0 ]
then
echo The given number $n is even
else
echo The given number $n is odd
fi

Output:
algin@ubuntu:~/shell$ sh odd.sh Enter a number
4
The given number 4 is even algin@ubuntu:~/shell$ sh odd.sh Enter a number
9
The given number 9 is odd

Result:
Thus, the shell program to check whether a given number is odd or even has been executed andverified.
Date :
Exercise Number : 2.f
Title: Check positive, negative or zero

Aim:
To write a shell program to check whether a given number is positive, negative or zero.

Algorithm:
Step 1: Start the process.
Step 2: Read the input value n.
Step 3: Check if n > 0 then print “The given no is Positive” and go to step 6 else go to step 4. Step 4: Check if
n< 0 then print “The given no is Negative” and go to step 6 else go to step 5. Step 5: Print “The given no is
Zero”.
Step 6: Stop the process.

Program:
#shell script to check whether a given number is positive, negative or zero

echo enter a number


read n
if [ $n -gt 0 ]
then
echo The given number $n is a positive number
elif [ $n -lt 0 ]
then
echo The given number $n is a negative number
else
echo The given number is zero
fi

Output:
algin@ubuntu:~/shell$ sh pos_neg_zero.sh enter a number 68
The given number 68 is a positive number algin@ubuntu:~/shell$ sh pos_neg_zero.sh enter a number -21
The given number -21 is a negative number algin@ubuntu:~/shell$ sh pos_neg_zero.sh enter a number 0
The given number is zero

Result:
Thus, the shell program to check whether a given number is positive, negative or zero has been executed and
verified
Date :
Exercise Number : 2.g
Title:Basic arithmetic operations

Aim:
To write a shell program to perform the basic arithmetic operations.

Algorithm:
Step 1: Start the process.
Step 2: Read the input numbers 'a' and 'b' and the choice,
1.Add 2. Subtract 3.Multiply 4.Divide 5. Exit.
Step 3: If choice = 1 then find sum=a+b and print the sum.
Step 4: If choice = 2 then find difference=a-b and print the difference.
Step 5: If choice = 3 then find product=a*b and print the product.
Step 6: If choice = 4 then find quotient=a/b and print the quotient. Step 7: If choice = 5 then stop the process.

Program:
#shell program to perform the basic arithmetic operations
echo Enter the two numbers
read a b
echo "Menu\n 1.Add\n 2.Subtract\n 3.Multiply\n 4.Divide\n 5.Exit\n"
echo Enter your choice:
read choice
case $choice in
1) sum=`expr $a + $b`
echo The sum of $a and $b is $sum;;
2) difference=`expr $a - $b`
echo The differenceof $a and $b is $difference;;
3) product=`expr $a \* $b`
echo The product of $a and $b is $product;;
4) quotient=`expr $a / $b`
echo The quotient when $a is divided by $b is $quotient;;
5) echo bye
exit;;
Esac

Output:
algin@ubuntu:~/shell$ sh arithmetic.sh Enter the two numbers
56
Menu 1.Add 2.Subtract 3.Multiply 4.Divide 5.Exit
Enter your choice:
1
The sum of 5 and 6 is 11 algin@ubuntu:~/shell$ sh arithmetic.sh Enter the two numbers
23 15
Menu 1.Add 2.Subtract 3.Multiply 4.Divide 5.Exit
Enter your choice:
2
The difference of 23 and 15 is 8 algin@ubuntu:~/shell$ sh arithmetic.sh Enter the two numbers
20 2
Menu 1.Add 2.Subtract 3.Multiply 4.Divide 5.Exit
Enter your choice:
3
The product of 20 and 2 is 40
algin@ubuntu:~/shell$ sh arithmetic.sh Enter the two numbers
21 3
Menu 1.Add 2.Subtract 3.Multiply

4.Divide 5.Exit
Enter your choice:
4
The quotient when 21 is divided by 3 is 7

Result:
Thus, the shell program to perform the basic arithmetic operations has been executed and
verified.
Date :
Exercise Number : 2.h
Title: Sum of first five natural number

Aim:
To write shell script to calculate the sum and to print the first five natural numbers.

Algorithm:
Step 1: Start the process.
Step 2: Assign sum=0.
Step 3: From 1 to 5 add the numbers with sum.
Step 4: Print the natural numbers from 1 to 5 and print their sum.
Step 5: Stop the process.

Program:
# shell program to calculate the sum and to print the first 5 natural numbers
sum=0
echo The first five natural numbers:
for i in 1 2 3 4 5 do
sum=`expr $sum + $i`
echo $i
done
echo The sum of first 5 natural numbers is $sum

Output:
algin@ubuntu:~/shell$ sh sumn.sh The first five natural numbers:
1
2
3
4
5
The sum of first 5 natural numbers is 15

Result:
Thus, the shell program to calculate the sum and to print the first five natural numbers has been executed and
verified.
Date :
Exercise Number : 2.i
Title:Sum of odd numbers up to n

AIM:
To write a Shell program to print and to calculate the sum of odd numbers up to n using until loop.

ALGORITHM:
Step 1: Start the process.
Step 2: Read the input value n.
Step 3: Initialize i value as 1, sum as 0 and j as 0.
Step 4: Do until i>n then go to step 5 else go to step 6.
Step 5: Calculate sum=sum+i, j=j+1, i= i+2 and go to step 4. Step 6: Print the odd numbers up to n and print
sum of them. Step 7: Stop the process.

PROGRAM:
#shell program to print and to calculate the sum of odd numbers upto n using until loop
echo "Enter the n value\t:"
read n i=1
sum=0
j=0
until [ $i -gt $n ]
do
echo " $i\t"
sum=`expr $sum + $i`
j=`expr $j + 1`
i=`expr $i + 2`
done
echo The sum of the first $j odd numbers upto $n is $sum

OUTPUT:
algin@ubuntu:~/shell$ sh sumodd.sh Enter the n value : 10
1
3
5
7
9
The sum of the first 5 odd numbers upto 10 is 25

RESULT:
Thus, the shell program to print and to calculate the sum of odd numbers up to n using until loop has been
executed and verified.
Date :
Exercise Number : 2.j
Title: Sum of odd numbers up to n

Aim:
To write a shell program to print and to calculate the sum of even numbers up to n using while loop.

Algorithm:
Step 1: Start the process.
Step 2: Read the input value n.
Step 3: Initialize Me value as 2, sum as 0 and j as 0.
Step 4: Check if I<n then go to step 5 else go to step 6.
Step 5: Calculate sum=sum+i, j=j+1, i= i+2 and go to step 4.
Step 6: Print the even numbers up to n and print sum of them
Step 7: Stop the process.

Program:
#shell program to print and to calculate the sum of even numbers upto n using while loop
echo "Enter the n value\t:"
read n
i=2
sum=0
j=0
while [ $i -le $n ]
do
echo " $i\t"
sum=`expr $sum + $i`
j=`expr $j + 1`
i=`expr $i + 2`
done
echo "\nThe sum of first $j even numbers upto $n is $sum"

Output:
algin@ubuntu:~/shell$ sh sumeven.sh Enter the n value : 10
2
4
6
8
10
The sum of first 5 even numbers upto 10 is 30

Result:
Thus, the shell program to print and to calculate the sum of even numbers up to n using while loop has been
executed and verified.
Date :
Exercise Number : 2.k
Title:Factorial of a given number

Aim:
To write a shell program to find factorial of a given number using while loop.

Algorithm:
Step 1: Start the process.
Step 2: Read the input value n.
Step 3: Initialize i value as 1, fact as 1.
Step 4: Check if i<n then go to step 5 else go to step 6. Step 5: Calculate fact=fact*i and i=i+1 and go to step
4. Step 6: Print the factorial of given number n.
Step 7: Stop the process.

Program:
#shell program to find factorial of a given number using while loop
echo Enter a number
read n
i=1
fact=1
while [ $i -le $n ]
do
fact=`expr $fact \* $i`
i=`expr $i + 1`
done
echo Factorial value of $n is $fact

Output:
algin@ubuntu:~/shell$ sh fact.sh Enter a number
5
Factorial value of 5 is 120

Result:
Thus, the shell program to find factorial of a given number using while loop has been executed and verified.
Date :
Exercise Number : 2.l
Title: Check armstrong number or not
Aim:
To write Shell script to check whether a given number is armstrong or not.

Algorithm:
Step 1: Start the process.
Step 2: Read the input value n.
Step 3: Initialize sum as 0 and x as n.
Step 4: Check if n>0 then go to step 5 else go to step 6.
Step 5: Calculate y=n%10, z=y*y*y, sum=sum+z, n=n/10 and go to step 4.
Step 6: Check if x=sum then Print “The given number is Armstrong” and go to step 7 else print “ The given
number is not Armstrong” and go to step 7.
Step 7: Stop the process.

Program:
#Shell program to check whether a given number is armstrong or not.

echo enter a number


read n
x=$n
sum=0
while [ $n -gt 0 ]
do
y=`expr $n % 10`
z=`expr $y \* $y \* $y`
sum=`expr $sum + $z`
n=`expr $n / 10`
done
if [ $x -eq $sum ]
then
echo $x is an armstrong number
else
echo $x is not an armstrong number
fi

Output:
algin@ubuntu:~/shell$ sh arm.sh
enter a number 123
123 is not an armstrong number
algin@ubuntu:~/shell$ sh arm.sh
enter a number 153
153 is an armstrong number

Result: Thus, the shell program to check whether a given number is Armstrong or not has been
executed and verified.
Ex. No. : 3 Programs for Unix System Calls
Date :
Exercise Number : 3.a
Title: Imitate the action of “ls” command
Aim:
To execute a program for system calls which reads the content of the root directory in c program.
Algorithm:
STEP1: Start the program
STEP 2: Declare the necessary header files,
STEP3: Declare the structure
STEP 4: Open the file in read mode
STEP 5: Print the contents of the root directory
STEP 6: Close the file
Program:

#include <stdio.h>
#include <dirent.h>
main()
{
struct dirent **namelist;
int n,i;
char pathname[100];
getcwd(pathname);
n = scandir(pathname, &namelist, 0, alphasort);
if(n < 0)
printf("Error\n");
else
for(i=0; i<n; i++) if(namelist[i]->d_name[0] != '.')
printf("%-20s", namelist[i]->d_name);
}
Output:
apache2 lock log mount node_modules programiz-oc pty.node
secrets sendsigs.omit.d shm swift-5.7.2-RELEASE-ubuntu22.04swift.tar.gz systemd
user
RESULT:
Thus, the C program to read the contents of the root directory is executed successfully.
Date :
Exercise Number : 3.b
Title: Use system calls to imitate the action of UNIX command "grep"

Aim:
To implement system calls to imitate the action of UNIX command "grep".

Algorithm:
STEP 1: Start the program.
STEP 2: Create struct dirent.
STEP 3: declare the variable buff and pointer dptr.
STEP 4: Get the directory name.
STEP 5: Open the directory.
STEP 6: Read the contents in directory and print it.
STEP 7: Close the directory.

Program:
#include<stdio.h>
#include<dirent.h>
int main() {
char fn[10], pat[10], temp[200];
FILE *fp;
printf("\n Enter file name : ");
scanf("%s", fn);
printf("Enter the pattern: ");
scanf("%s", pat);
fp = fopen(fn, "r");
while (!feof(fp))
{
fgets(temp, sizeof(fp), fp);
if (strcmp(temp, pat))
printf("%s", temp);
}
fclose(fp);
return 1;
}
Output:
Enter file name : program.c
Enter the pattern: while
while (!feof(fp))
{
fgets(temp, sizeof(fp), fp);
if (strcmp(temp, pat))
printf("%s", temp);
}

RESULT: Thus, the system call have been implemented successfully.


Date :
Exercise Number : 3.c
Title: Implement process life cycle

Aim: To implement system calls in C Programming.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Create struct dirent.
STEP 3: declare the variable buff and pointer dptr.
STEP 4: Get the directory name.
STEP 5: Open the directory.
STEP 6: Read the contents in directory and print it.
STEP 7: Close the directory.

PROGRAM:
#include<stdio.h> // printf()
#include<stdlib.h> // exit()
#include<sys/types.h> // pid_t
#include<sys/wait.h> // wait()
#include<unistd.h> // fork
int main(int argc, char **argv)
{
pid_t pid;
pid = fork();
if(pid==0)
{
printf("It is the child process and pid is %d\n",getpid());
int i=0;
for(i=0;i<8;i++)
{
printf("%d\n",i);
}
exit(0);
}
else if(pid > 0)
{
printf("It is the parent process and pid is %d\n",getpid());
int status;
wait(&status);
printf("Child is reaped\n");
}
else
{
printf("Error in forking..\n");
exit(EXIT_FAILURE);
}
return 0;
}
Output
It is the parent process and pid is 53398
It is the child process and pid is 53399
0
1
2
3
4
5
6
7
Child is reaped

Result:
Thus, the program for process life cycle is implemented successfully.
Ex. No. : 4 Implement P-Threads And Synchronization
Date:
Aim:
To write a C program to implement Threading & Synchronization

Algorithm:
Step 1: Start the Program
Step 2: Obtain the required data through char and in data types.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
Program:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

pthread_t tid[2];
intcounter;

void* trythis(void* arg)


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

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


;
printf("\n Job %d has finished\n", counter);

returnNULL;
}

intmain(void)
{
inti = 0;
interror;

while(i < 2) {
error = pthread_create(&(tid[i]), NULL, &trythis, NULL);
if(error != 0)
printf("\nThread can't be created : [%s]", strerror(error));
i++;
}

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

return0;
}
Output:
Job 1 has started
Job 2 has started
Job 2 has finished
Job 2 has finished

Result:
Thus, the program for creating thread and synchronization using p thread is executed successfully.
Ex. No. : 5 Implement Semaphores
Date:
Aim:
To write a C program to implement the semaphores.

ALGORITHM:
1. Start the process
2. Initialize buffer size
3. Consumer enters, before that producer buffer was not empty.
4. Producer enters, before check consumer consumes the buffer.
5. Stop the process.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("1.PRODUCER\n 2.CONSUMER\n 3.EXIT\n");
while(1)
{
printf("ENTER YOUR CHOICE\n");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1 && empty!=0))
producer();
else
printf("BUFFER IS FULL\n");
break;
case 2:
if((mutex==1 && full!=0))
consumer();
else
printf("BUFFER IS EMPTY\n");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("producer produces the item %d \n",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("consumer consumes item %d \n",x);
x--;
mutex=signal(mutex);
}
OUTPUT:
[root@localhost ~]# ./a.out
1.PRODUCER
2.CONSUMER
3.EXIT
ENTER YOUR CHOICE
1producer produces the item1
ENTER YOUR CHOICE
1producer produces the item2
ENTER YOUR CHOICE
2consumer consumes item2
ENTER YOUR CHOICE
2consumer consumes item1
ENTER YOUR CHOICE
2
BUFFER IS EMPTY
ENTER YOUR CHOICE
3

RESULT:
Thus the program for Implement the Producer – Consumer problem using semaphores (using UNIX system
calls) was written and successfully executed.
Ex. No. : 6 Implement IPC using Shared memory
Date:
AIM:
To write a program for developing Application using Inter Process communication with pipes.

ALGORITHM:
Step 1: Start the process
Step 2: Declare the segment size
Step 3: Create the shared memory
Step 4: Read the data from the shared memory
Step 5: Write the data to the shared memory
Step 6: Edit the data
Step 7: Stop the process

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#define SEGSIZE 100
int main(int argc, char *argv[ ])
{
int shmid,cntr;
key_t key;
char *segptr;
char buff[]="poooda......";
key=ftok(".",'s');
if((shmid=shmget(key, SEGSIZE, IPC_CREAT | IPC_EXCL | 0666))== -1)
{
if((shmid=shmget(key,SEGSIZE,0))==-1)
{
perror("shmget");
exit(1);
}}
else
{
printf("Creating a new shared memory seg \n");
printf("SHMID:%d",shmid);
}
system("ipcs –m");
if((segptr=(char*)shmat(shmid,0,0))==(char*)-1)
{
perror("shmat");
exit(1);
}
printf("Writing data to shared memory…\n");
strcpy(segptr,buff);
printf("DONE\n");
printf("Reading data from shared memory…\n");
printf("DATA:-%s\n",segptr);
printf("DONE\n");
printf("Removing shared memory Segment…\n");
if(shmctl(shmid,IPC_RMID,0)== -1)
printf("Can‟t Remove Shared memory Segment…\n");
else
printf("Removed Successfully");
}
Output
Creating a new shared memory seg
------ Message Queues --------
key msqid owner perms used-bytes messages
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x73d6fa24 0 compiler 666 100 0

------ Semaphore Arrays --------


key semid owner perms nsems

SHMID:0Writing data to shared memory…


DONE
Reading data from shared memory…
DATA:-poooda......
DONE
Removing shared memory Segment…
Removed Successfully
Ex. No. : 7 Implement IPC Using Message Queue
Date:
Aim:
To implement IPC using message queue.

Algorithm:
Step 1: Start the Program
Step 2: Obtain the required data through char and int datatypes.
Step 3: Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5: Fill is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution

Program:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define MAX_TEXT 512 //maximum length of the message that can be sent allowed
struct my_msg{
long int msg_type;
char some_text[MAX_TEXT];
};
int main()
{
int running=1;
int msgid;
struct my_msg some_data;
char buffer[50]; //array to store user input
msgid=msgget((key_t)14534,0666|IPC_CREAT);
if (msgid == -1) // -1 means the message queue is not created
{
printf("Error in creating queue\n");
exit(0);
}
while(running)
{
printf("Enter some text:\n");
fgets(buffer,50,stdin);
some_data.msg_type=1;
strcpy(some_data.some_text,buffer);
if(msgsnd(msgid,(void *)&some_data, MAX_TEXT,0)==-1) // msgsnd returns -1
{
printf("Msg not sent\n");
}
if(strncmp(buffer,"end",3)==0)
{
running=0;
}
}}
Output:

Enter some text:


data
Enter some text:
validation
Enter some text:
manipulation
Enter some text:
end

Result:
Thus, the program for implementing IPC using message queue is executed successfully.
Ex. No. : 8 Scheduling algorithms
Date :
Exercise Number : 8.a
Title: Scheduling algorithms - First Come First Serve Scheduling Algorithm

Aim:
To schedule the process based on FCFS Scheduling algorithm.

Algorithm:
1. Initialize the variables .
2. Get the number of processes.
3. Get the burst times.
4. Calculate turnaround time and waiting time
5. Find the average turn around time and waiting time and print them.

Program:

#include<stdio.h>
#include<string.h>
main()
{
int i,j,np,b[100],wt[100],tat[100],twt=0,temp,l,ttat=0;
float awt=0.0;
char p[10][10],tem[10];
printf("ENTER NO OF PROCESS:");
scanf("%d",&np);
printf("ENTER PROCESS NAME:");
for(i=0;i<np;i++)
{
scanf("%s",p[i]);
}
for(i=0;i<np;i++)
{
printf("ENTER BURST TIME FOR %s:",p[i]);
scanf("%d",&b[i]);
}
wt[0]=0;
for(i=1;i<np;i++)
{
wt[i]=wt[i-1]+b[i-1];
twt=twt+wt[i];
}
for(i=0;i<np;i++)
{
tat[i]=wt[i]+b[i];
ttat=ttat+tat[i];
}
awt=(float)twt/(float)np;
printf("\nPROCESS\t BURST TIME\tWAITING TIME\tTURN AROUND TIME:\n");
for(i=0;i<np;i++)
{
printf("%s\t d\t\t%d\t\t%d\n",p[i],b[i],wt[i],tat[i]);
}
printf("TOTAL WAITING TIME:%d",twt);
printf("\nAVERAGE WAITING TIME:%f",awt);
printf("\ngantt chart:\n");
l=strlen(p[1]);
for(i=0;i<=tat[np-1]+(np*l);i++)
{
printf("-");
}
printf("\n|");
j=0;
for(i=1;i<=tat[np-1]+(np*l);i++)
{
if(i==tat[j])
{
printf("%s|",p[j]);
j++;
}
else
printf(" ");
}
printf("\n");
for(i=0;i<=tat[np-1]+(np*l);i++)
{
printf("-");
}
printf("\n0");
j=0;
for(i=1;i<tat[np-1]+(np*l);i++)
{
if(i==tat[j]+l*(j))
{
printf("%d",tat[j]);
j++;
}
else
printf(" ");
}
}

Output:
ENTER NO OF PROCESS:5
ENTER PROCESS NAME:p1
p2
p3
p4
p5
ENTER BURST TIME FOR p1:3
ENTER BURST TIME FOR p2:2
ENTER BURST TIME FOR p3:5
ENTER BURST TIME FOR p4:7
ENTER BURST TIME FOR p5:1
PROCESS BURST TIME WAITING TIME TURN AROUND TIME:
p1 3 0 3
p2 2 3 5
p3 5 5 10
p4 7 10 17
p5 1 17 18

TOTAL WAITING TIME:35


AVERAGE WAITING TIME:7.000000

Gantt chart:
-----------------------------
| p1| p2| p3| p4|p5|
-----------------------------
0 3 5 10 17 18

Result:
Thus, the FCFS algorithm is implemented successfully.
Date :
Exercise Number : 8.b
Title: Scheduling algorithms - Shortest Job First

Aim
To schedule the process based on SJF Scheduling algorithm.

Algorithm
1. Initialize the variables.
2. Get the number of processes.
3. Get the burst times.
4. Arrange the jobs based on their burst times with the job with the shortest burst
time first.
5. Calculate turn around time and waiting time
6. Find the average turn around time and waiting time and print them.

Program
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,np,b[100],wt[100],tat[100],twt=0,temp,l;
float awt=0.0;
char p[10][10],tem[10];
printf("ENTER NO OF PROCESS:");
scanf("%d",&np);
printf("ENTER PROCESS NAME:");
for(i=0;i<np;i++)
{
scanf("%s",p[i]);
}
for(i=0;i<np;i++)
{
printf("ENTER BURST TIME: %s:",p[i]);
scanf("%d",&b[i]);
}
for(i=0;i<np-1;i++)
{
for(j=i+1;j<np;j++)
{
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
strcpy(tem,p[j]);
strcpy(p[j],p[i]);
strcpy(p[i],tem);
}
}
}
wt[0]=0;
for(i=1;i<np;i++)
{
wt[i]=wt[i-1]+b[i-1];
twt=twt+wt[i];
}
for(i=0;i<np;i++)
{
tat[i]=wt[i]+b[i];
}
awt=(float)twt/(float)np;
printf("\nPROCESS\t BURST TIME\tWAITING TIME\tTURN AROUND TIME:\n");
for(i=0;i<np;i++)
{
printf("%s\t %d\t\t%d\t\t%d\n",p[i],b[i],
wt[i],tat[i]);
}
printf("TOTAL WAITING TIME:%d",twt);
printf("\nAVERAGE WAITING TIME:%f",awt);
printf("\ngantt chart:\n");
l=strlen(p[1]);
for(i=0;i<=tat[np-1]+(np*l);i++)
{
printf("-");
}
printf("\n|");
j=0;
for(i=1;i<=tat[np-1]+(np*l);i++)
{
if(i==tat[j])
{
printf("%s|",p[j]);
j++;
}
else
printf(" ");
}
printf("\n");
for(i=0;i<=tat[np-1]+(np*l);i++)
{
printf("-");
}
printf("\n0");
j=0;
for(i=1;i<tat[np-1]+(np*l);i++)
{
if(i==tat[j]+l*(j))
{
printf("%d",tat[j]);
j++;
}
else
printf(" ");
}
}
Output:
ENTER NO OF PROCESS:5
ENTER PROCESS NAME:p1
p2
p3
p4
p5
ENTER BURST TIME: p1:4
ENTER BURST TIME: p2:2
ENTER BURST TIME: p3:7
ENTER BURST TIME: p4:1
ENTER BURST TIME: p5:3
PROCESS BURSTTIME WAITING TIME TURNAROUNDTIME:
p4 1 0 1
p2 2 1 3
p5 3 3 6
p1 4 6 10
p3 7 10 17
TOTAL WAITING TIME:20
AVERAGE WAITING TIME:4.000000
Gantt chart:
----------------------------
|p4| p2| p5| p1| p3|
----------------------------
01 3 6 10 17

Result:
Thus, the program for SJF scheduling algorithm is executed successfully.
Date :
Exercise Number : 8.c
Title: Scheduling algorithms - Priority Scheduling Algorithm
Aim
To schedule the process based on Priority Scheduling algorithm.
Algorithm
1. Initialize the variables.
2. Get the no of processes.
3. Get their burst times.
4. Get their priority.
5. Arrange the jobs based on their priority.
6. Calculate turn around time and waiting time.
7. Find the average turn around time and waiting time and print them.
Program
#include<stdio.h>
#include<string.h>
main()
{
int i,j,np,b[100],wt[100],tat[100],twt=0,temp,l,pr[10],t;
float awt=0.0;
char p[10][10],tem[10];
printf("ENTER NO OF PROCESS:");
scanf("%d",&np);
printf("ENTER PROCESS NAME:");
for(i=0;i<np;i++)
{
scanf("%s",p[i]);
}
for(i=0;i<np;i++)
{
printf("ENTER BURST TIME %s:",p[i]);
scanf("%d",&b[i]);
}
for(i=0;i<np;i++)
{
printf("ENTER %s PRIORITY:",p[i]);
scanf("%d",&pr[i]);
}
for(i=0;i<np-1;i++)
{
for(j=i+1;j<np;j++)
{
if(pr[i]>pr[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
strcpy(tem,p[j]);
strcpy(p[j],p[i]);
strcpy(p[i],tem);
t=pr[i];
pr[i]=pr[j];
pr[j]=t;
}
}
}
wt[0]=0;
for(i=1;i<np;i++)
{
wt[i]=wt[i-1]+b[i-1];
twt=twt+wt[i];
}
for(i=0;i<np;i++)
{
tat[i]=wt[i]+b[i];
}
awt=(float)twt/(float)np;
printf("\nPROCESS\t BURST TIME\tWAITING TIME\tTURN AROUND TIME:\n");
for(i=0;i<np;i++)
{
printf("%s\t %d\t\t%d\t\t%d\n",p[i],b[i],wt[i],tat[i]);
}
printf("TOTAL WAITING TIME:%d",twt);
printf("\nAVERAGE WAITING TIME:%f",awt);
printf("\ngantt chart:\n");
l=strlen(p[1]);
for(i=0;i<=tat[np-1]+(np*l);i++)
{
printf("-");
}
printf("\n|");
j=0;
for(i=1;i<=tat[np-1]+(np*l);i++)
{
if(i==tat[j])
{
printf("%s|",p[j]);
j++;
}
else
printf(" ");
}
printf("\n");
for(i=0;i<=tat[np-1]+(np*l);i++)
{
printf("-");
}
printf("\n0");
j=0;
for(i=1;i<tat[np-1]+(np*l);i++)
{
if(i==tat[j]+l*(j))
{
printf("%d",tat[j]);
j++;
}
else
printf(" ");
}
}
Output:
ENTER NO OF PROCESS:5
ENTER PROCESS NAME:p1
p2
p3
p4
p5
ENTER BURST TIME p1:3
ENTER BURST TIME p2:5
ENTER BURST TIME p3:6
ENTER BURST TIME p4:4
ENTER BURST TIME p5:1
ENTER p1 PRIORITY:3
ENTER p2 PRIORITY:1
ENTER p3 PRIORITY:4
ENTER p4 PRIORITY:5
ENTER p5 PRIORITY:2

PROCESS BURST TIME WAITING TIME TURN AROUND TIME:


p2 5 0 5
p5 1 5 6
p1 3 6 9
p3 6 9 15
p4 4 15 19
TOTAL WAITING TIME:35
AVERAGE WAITING TIME:7.000000
Gantt chart:
------------------------------
| p2|p5| p1| p3| p4|
------------------------------
0 5 6 9 15 19 */

Result:
Thus the scheduling algorithm is executed successfully.
Date :
Exercise Number : 8.d
Title: Scheduling algorithms - Round Robin Scheduling

Aim
To schedule the process based on Round Robin Scheduling algorithm.
Algorithm
1. Initialize the variables.
2. Get the no of jobs.
3. Get the burst times.
4. Get the time slice.
5. Calculate turn around time and waiting time.
6. Find the average turn around time and waiting time and print them.
Program
#include<stdio.h>
main()
{
int i,n,process[10],burst[10], arrival[10], temp_comp[10], wait[10], turn[10], finish[10], count,
ctime=0, tslice, tot_wait=0, tot_turn=0;
boolean flag[10];

printf(“\n Enter the no. of processe \n”);


scanf(“%d”, &n);
count=n;

printf(“\n Enter the time slice\n”);


scanf(“%d”, &tslice);

for (i=1;i<=n;i++)
{
printf(“\n Enter the process id and burst time for the %d process”,i);
scanf(“%d%d”, &process[i],&burst[i]);
arrival[i]=0;
temp_comp[i]=0;
wait[i]=0;
turn[i]=0;
flag[i]=false;
}
while(count>0)
{
for (i=1;i<=n;i++)
{
if (flag[i]==false)
{
wait[i]=wait[i]+(ctime-temp_comp[i]);
if (burst[i]<=tslice)
{
ctime=ctime+burst[i];
burst[i]=0;
finish[i]=ctime;
}
else
{
ctime=ctime+tslice;
burst[i]=burst[i]-tslice;
}
temp_comp[i]=ctime;
if (burst[i]==0)
{
flag[i]=true;
count=count-1;
}
}
}
}
printf(“\n Process\tBurstTime\t WaitingTime\t TurnAroundTime”);
for(i=1;i<=n;i++)
{
turn[i]=finish[i]-arrival[i];
tot_wait=tot_wait+wait[i];
tot_turn=tot_turn+turn[i];
printf(“\t%d\t%d\t%d\t%d”,process[i], burst[i], wait[i], turn[i]);
}
printf(“\n Average Waiting time is %d \n Average Turn around time is %d”, (tot_wait/n), (tot_turn/n));
}
Output:
$ ./a.out
Enter the number of jobs 5
Enter the 0 th burst time 6
Enter the 1 th burst time 9
Enter the 2 th burst time 7
Enter the 3 th burst time 3
Enter the 4 th burst time 7
Enter the time slice 2
job burst AT start finish WT TAT
0 9 0 0 9 0 9
1 6 0 9 15 9 15
3 3 0 18 15 18 18
4 7 0 18 25 18 25
2 7 0 25 32 25 32
Avg turn around = 19
Avg waiting time = 13

Result:
Thus, the CPU scheduling algorithms are implemented successfully.
Ex. No. : 9 Implement bankers algorithm for deadlock avoidance
Date:
AIM:
To write a C program to implement deadlock detection algorithm.

ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and in data types.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution

PROGRAM:
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
int avail[3] = { 3, 3, 2 }; // Available Resources
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++)
{
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
}
}
if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}
return (0);
}

OUTPUT:
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2

RESULT:
Thus the program for deadlock detection algorithm was written and successfully executed.
Ex. No. : 10 Implementation For Memory Management
Exercise Number : 10.a
Title: Implementation Of Memory Management Schemes –First Fit

AIM:
To write a program to implement first fit algorithm for memory management.

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

PROGRAM:
#include <stdio.h>

void implimentFirstFit(int blockSize[], int blocks, int processSize[], int processes)


{
// This will store the block id of the allocated block to a process
int allocate[processes];
int occupied[blocks];

// initially assigning -1 to all allocation indexes


// means nothing is allocated currently
for(int i = 0; i < processes; i++)
{
allocate[i] = -1;
}

for(int i = 0; i < blocks; i++){


occupied[i] = 0;
}

// take each process one by one and find


// first block that can accomodate it
for (int i = 0; i < processes; i++)
{
for (int j = 0; j < blocks; j++)
{
if (!occupied[j] && blockSize[j] >= processSize[i])
{
// allocate block j to p[i] process
allocate[i] = j;
occupied[j] = 1;

break;
}
}
}

printf("\nProcess No.\tProcess Size\tBlock no.\n");


for (int i = 0; i < processes; i++)
{
printf("%d \t\t\t %d \t\t\t", i+1, processSize[i]);
if (allocate[i] != -1)
printf("%d\n",allocate[i] + 1);
else
printf("Not Allocated\n");
}
}

void main()
{
int blockSize[] = {30, 5, 10};
int processSize[] = {10, 6, 9};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);
implimentFirstFit(blockSize, m, processSize, n);
}

OUTPUT:
Process No. Process Size Block no.
1 10 1
2 6 3
3 9 Not Allocated

RESULT:
Thus the program for Implement first fit algorithm for memory management is written and
successfully executed.
Date :
Exercise Number : 10.b
Title: Implementation Of Memory Management Schemes – Best FitAlgorithm
AIM:
To write a program for Implement best fit memory management.

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

PROGRAM:
#include <stdio.h>

void implimentBestFit(int blockSize[], int blocks, int processSize[], int proccesses)


{
// This will store the block id of the allocated block to a process
int allocation[proccesses];
int occupied[blocks];

// initially assigning -1 to all allocation indexes


// means nothing is allocated currently
for(int i = 0; i < proccesses; i++){
allocation[i] = -1;
}

for(int i = 0; i < blocks; i++){


occupied[i] = 0;
}

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i = 0; i < proccesses; i++)
{

int indexPlaced = -1;


for (int j = 0; j < blocks; j++) {
if (blockSize[j] >= processSize[i] && !occupied[j])
{
// place it at the first block fit to accomodate process
if (indexPlaced == -1)
indexPlaced = j;

// if any future block is smalller than the current block where


// process is placed, change the block and thus indexPlaced
// this reduces the wastage thus best fit
else if (blockSize[j] < blockSize[indexPlaced])
indexPlaced = j;
}
}
// If we were successfully able to find block for the process
if (indexPlaced != -1)
{
// allocate this block j to process p[i]
allocation[i] = indexPlaced;

// make the status of the block as occupied


occupied[indexPlaced] = 1;
}
}

printf("\nProcess No.\tProcess Size\tBlock no.\n");


for (int i = 0; i < proccesses; i++)
{
printf("%d \t\t\t %d \t\t\t", i+1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n",allocation[i] + 1);
else
printf("Not Allocated\n");
}
}

// Driver code
int main()
{
int blockSize[] = {100, 50, 30, 120, 35};
int processSize[] = {40, 10, 30, 60};
int blocks = sizeof(blockSize)/sizeof(blockSize[0]);
int proccesses = sizeof(processSize)/sizeof(processSize[0]);

implimentBestFit(blockSize, blocks, processSize, proccesses);

return 0 ;
}

OUTPUT:
Process No. Process Size Block no.
1 40 2
2 10 3
3 30 5
4 60 1
RESULT:
Thus the program for Implement best fit algorithm for memory management is written and
successfully executed.
Date :
Exercise Number : 10.c
Title: Implementation of memory management schemes – Worst Fit Algorithm

AIM:
To write a program for Implement worst fit memory management.

ALGORITHM:
1. Start the program.
2. Declare the size.
3. Get the number of processes to be inserted.
4. Allocate the first hole that is small enough searching.
5. If small enough then stop searching in the procedure.
6. Display the values.
7. Stop the program.

PROGRAM:
#include <stdio.h>

void implimentWorstFit(int blockSize[], int blocks, int processSize[], int processes)


{
// This will store the block id of the allocated block to a process
int allocation[processes];
int occupied[blocks];

// initially assigning -1 to all allocation indexes


// means nothing is allocated currently
for(int i = 0; i < processes; i++){
allocation[i] = -1;
}

for(int i = 0; i < blocks; i++){


occupied[i] = 0;
}

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i=0; i < processes; i++)
{
int indexPlaced = -1;
for(int j = 0; j < blocks; j++)
{
// if not occupied and block size is large enough
if(blockSize[j] >= processSize[i] && !occupied[j])
{
// place it at the first block fit to accomodate process
if (indexPlaced == -1)
indexPlaced = j;

// if any future block is larger than the current block where


// process is placed, change the block and thus indexPlaced
else if (blockSize[indexPlaced] < blockSize[j])
indexPlaced = j;
}
}

// If we were successfully able to find block for the process


if (indexPlaced != -1)
{
// allocate this block j to process p[i]
allocation[i] = indexPlaced;

// make the status of the block as occupied


occupied[indexPlaced] = 1;

// Reduce available memory for the block


blockSize[indexPlaced] -= processSize[i];
}
}

printf("\nProcess No.\tProcess Size\tBlock no.\n");


for (int i = 0; i < processes; i++)
{
printf("%d \t\t\t %d \t\t\t", i+1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n",allocation[i] + 1);
else
printf("Not Allocated\n");
}
}

// Driver code
int main()
{
int blockSize[] = {100, 50, 30, 120, 35};
int processSize[] = {40, 10, 30, 60};
int blocks = sizeof(blockSize)/sizeof(blockSize[0]);
int processes = sizeof(processSize)/sizeof(processSize[0]);

implimentWorstFit(blockSize, blocks, processSize, processes);

return 0;
}

OUTPUT:
Process No. Process Size Block no.
1 40 4
2 10 1
3 30 2
4 60 Not Allocated

RESULT:
Thus the program for Implement best fit algorithm for memory management is written and
successfully executed.
Ex. No. : 11 Implement Paging Technique Of Memory Management
Date:
AIM:
To write a c program to implement Paging technique for memory management.

ALGORITHM:
Step 1: Start the process
Step 2: Declare page size,nofpage, offset, frame no and process size.
Step 3: Read the page size, total number of pages
Step 4: Read the logiacal address
Step 5: Calculate the physical address
Step 6: Display the address
Step 7: Stop the process

PROGRAM:
#include<stdio.h>
void main()
{
int memsize=15;
int pagesize,nofpage;
int p[100];
int frameno,offset;
int logadd,phyadd;
int i;
int choice=0;
printf("\nYour memsize is %d ",memsize);
printf("\nEnter page size:");
scanf("%d",&pagesize);
nofpage=memsize/pagesize;
for(i=0;i<nofpage;i++)
{
printf("\nEnter the frame of page%d:",i+1);
scanf("%d",&p[i]);
}
do
{
printf("\nEnter a logical address:");
scanf("%d",&logadd);
frameno=logadd/pagesize;
offset=logadd%pagesize;
phyadd=(p[frameno]*pagesize)+offset;
printf("\nPhysical address is:%d",phyadd);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
}

Output:
Your memsize is 15
Enter page size:5
Enter the frame of page1:2
Enter the frame of page2:4
Enter the frame of page3:7
Enter a logical address:3
Physical address is:13
Do you want to continue(1/0)?:1
Enter a logical address:1
Physical address is:11
Do you want to continue(1/0)?:0

Result:
Thus the program for Implement Paging Technique of memory management is written and
successfully executed.
Ex. No. : 12 Implement Page Replacement Algorithms

Date:
Exercise Number: 12.a
Title: Implement the page replacement algorithm based on FIFO
AIM:
To write a C program for implementation of FIFO page replacement algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the necessary variables.
Step 3: Enter the number of frames.
Step 4: Enter the reference string end with zero.
Step 5: FIFO page replacement selects the page that has been in memory the longest time
Step 6: When a page is brought into memory, it is inserted at the tail of the queue.
Step 7: Initially all the three frames are empty.
Step 8: The page fault range increases as the no of allocated frames also increases.
Step 9: Print the total number of page faults.
Step 10: Stop the program.
PROGRAM:
#include <stdio.h>
int main()
{
int incomingStream[] = {4 , 1 , 2 , 4 , 5};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;
pages = sizeof(incomingStream)/sizeof(incomingStream[0]);
printf(" Incoming \ t Frame 1 \ t Frame 2 \ t Frame 3 ");
int temp[ frames ];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}
pageFaults++;
if((pageFaults <= frames) && (s == 0))
{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}
printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}
Output:
Incoming t Frame 1 t Frame 2 t Frame 3
4 4 - -
1 4 1 -
2 4 1 2
4 4 1 2
5 5 1 2
Total Page Faults: 4

RESULT:
Thus, the implementation of the page replacement algorithm based on FIFO is executed successfully.
Date :
Exercise Number : 12.b
Title: Implement the page replacement algorithm based on LRU

Aim:
To implement the page replacement algorithm based on LFU
Program:
#include <stdio.h>
//user-defined function
int findLRU(int time[], int n)
{
int i, minimum = time[0], pos = 0;

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


{
if (time[i] < minimum)
{
minimum = time[i];
pos = i;
}
}

return pos;
}

//main function
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j, pos,
faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

printf("Enter reference string: ");

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


{
scanf("%d", &pages[i]);
}

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


{
frames[i] = -1;
}

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


{
flag1 = flag2 = 0;

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


{
if (frames[j] == pages[i])
{
counter++;
time[j] = counter;
flag1 = flag2 = 1;
break;
}
}

if (flag1 == 0)
{
for (j = 0; j < no_of_frames; ++j)
{
if (frames[j] == -1)
{
counter++;
faults++;
frames[j] = pages[i];
time[j] = counter;
flag2 = 1;
break;
}
}
}

if (flag2 == 0)
{
pos = findLRU(time, no_of_frames);
counter++;
faults++;
frames[pos] = pages[i];
time[pos] = counter;
}

printf("\n");

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


{
printf("%d\t", frames[j]);
}
}

printf("\nTotal Page Faults = %d", faults);

return 0;
}

OUTPUT:
Enter number of frames: 3
Enter number of pages: 5
Enter reference string: 1 2 3 4 5
1 -1 -1
1 2 -1
1 2 3
4 2 3
4 5 3
Total Page Faults = 5

Result:
Thus, the implementation of the page replacement algorithm based on LRU is executed successfully.
Ex. No. : 13 Implement Disk Scheduling Algorithm

Aim:
To write a program for implementing disk scheduling algorithm.
Program:
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,sum=0,n;
int d[20];
int disk; //loc of head
int temp,max;
int dloc; //loc of disk in array
clrscr();
printf("enter number of location\t");
scanf("%d",&n);
printf("enter position of head\t");
scanf("%d",&disk);
printf("enter elements of disk queue\n");
for(i=0;i<n;i++)
{
scanf("%d",&d[i]);
}
d[n]=disk;
n=n+1;
for(i=0;i<n;i++) // sorting disk locations
{
for(j=i;j<n;j++)
{
if(d[i]>d[j])
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}

}
max=d[n];
for(i=0;i<n;i++) // to find loc of disc in array
{
if(disk==d[i]) { dloc=i; break; }
}
for(i=dloc;i>=0;i--)
{
printf("%d -->",d[i]);
}
printf("0 -->");
for(i=dloc+1;i<n;i++)
{
printf("%d-->",d[i]);
}
sum=disk+max;
printf("\nmovement of total cylinders %d",sum);
getch();
return 0;
}

Output:
Enter no of location 8
Enter position of head 53
Enter elements of disk queue
98
183
37
122
14
124
65
67
53->37->14->0->65->67->98->122->124->183->
Movement of total cylinders 236.

Result:
Thus, the program for disk scheduling is executed successfully.
Ex. No. : 14 Implement File Organization Techniques

Date :
Exercise Number : 14.a
Title: Implement File Organization Techniques- Single level directory

Aim:
To implement the file organization technique using single level directory.

Program:
#include<stdio.h> struct directory
{
char name[30]; int no;
char file[50][30];
};
int main()
{
struct directory dir[50]; int n,i,j;
printf("Enter the no. of Directories:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name of the Directory %d:",i+1); scanf("%s",dir[i].name);
printf("Enter the no.of files in the directory %s:",dir[i].name); scanf("%d",&dir[i].no);
if(dir[i].no!=0)
printf("Enter the file names:\n"); for(j=0;j<dir[i].no;j++)
scanf("%s",dir[i].file[j]);
}
printf("\nDirectory Structure..\n"); for(i=0;i<n;i++)
{
printf("%s\n",dir[i].name); for(j=0;j<dir[i].no;j++)

printf("\t%s\n",dir[i].file[j]);
}
return 0;
}
OUTPUT:
Enter the no. of Directories:2
Enter the name of the Directory 1:IIyear Enter the no.of files in the directory IIyear:3 Enter the file
names:
mpmc.txt os.txt daa.txt
Enter the name of the Directory 2:IIIyear Enter the no.of files in the directory IIIyear:3 Enter the file
names:
npm.txt cns.txt ooad.txt

Directory Structure..
IIyear
mpmc.txt os.txt daa.txt
IIIyear
npm.txt cns.txt ooad.txt

Result:
Thus the implementation of single level directory file organization technique is executed successfully.
Date :
Exercise Number : 14.b
Title: Implement File Organization Techniques- Two level directory

Aim:
To implement the file organisation technique using two level directory.
Program:
#include<stdio.h> struct subdirectory
{
char name[30]; int no;
char file[50][30];
};
struct directory
{
char name[30]; int nf,nsd;
struct subdirectory sd[50]; char file[50][30];
};
int main()
{
struct directory dir[50]; int n,i,j,k;
printf("Enter the no. of Directories:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name of the Directory %d:",i+1); scanf("%s",dir[i].name);
printf("Enter the no.of sub directories in the directory %s:",dir[i].name); scanf("%d",&dir[i].nsd);
if(dir[i].nsd!=0)

printf("Enter the details of sub directories:\n"); for(j=0;j<dir[i].nsd;j++)


{
printf("Enter the name of the Sub Directory %d:",i+1); scanf("%s",dir[i].sd[j].name);
printf("Enter the no.of files in the Sub Directory %s:",dir[i].sd[j].name); scanf("%d",&dir[i].sd[j].no);
if(dir[i].sd[i].no!=0)
printf("Enter the file names of the Sub Directory %s:\n",dir[i].sd[j].name);
for(k=0;k<dir[i].sd[j].no;k++)
scanf("%s",dir[i].sd[j].file[k]);
}
printf("Enter the no.of files in the directory %s:",dir[i].name); scanf("%d",&dir[i].nf);
if(dir[i].nf!=0)
printf("Enter the file names:\n"); for(j=0;j<dir[i].nf;j++)
scanf("%s",dir[i].file[j]);
}
printf("\nDirectory Structure..\n"); for(i=0;i<n;i++)
{
printf("%s\n",dir[i].name); for(j=0;j<dir[i].nsd;j++)
{
printf("\t%s\n",dir[i].sd[j].name);
for(k=0;k<dir[i].sd[j].no;k++)
printf("\t\t%s\n",dir[i].sd[j].file[k]);
}
for(j=0;j<dir[i].nf;j++) printf("\t%s\n",dir[i].file[j]);
}
return 0;
}

OUTPUT:
Enter the no. of Directories:2
Enter the name of the Directory 1:IT
Enter the no.of sub directories in the directory IT:2 Enter the details of sub directories:
Enter the name of the Sub Directory 1:IIyear Enter the no.of files in the Sub Directory IIyear:2 Enter
the file names of the Sub Directory IIyear: a.txt
b.txt
Enter the name of the Sub Directory 1:IIIyear Enter the no.of files in the Sub Directory IIIyear:1 Enter
the file names of the Sub Directory IIIyear: a.txt
Enter the no.of files in the directory IT:1 Enter the file names:
mark.doc
Enter the name of the Directory 2:CSE
Enter the no.of sub directories in the directory CSE:0 Enter the no.of files in the directory CSE:1
Enter the file names: staff.doc
Directory Structure.. IT

CSE

IIyear
a.txt b.txt
IIIyear
a.txt mark.doc

staff.doc

Result:
Thus, the implementation of two level directory file organization technique is executed successfully.
Date :
Exercise Number : 14.c
Title: Implement File Organization Techniques- Hierarchical

Aim:
To implement the file organisation technique using hierarchical level directory.
Program:
#include<stdio.h>
#include<stdlib.h>
struct directory;
struct directory
{
char name[30]; int nf,nsd;
struct directory *sub[50]; char file[50][30];
};
void mkdir(struct directory *dir)
{
int j;
printf("Enter the name of the Directory:"); scanf("%s",dir->name);
printf("Enter the no.of sub directories in the directory %s:",dir->name); scanf("%d",&dir->nsd);
if(dir->nsd!=0)
printf("Enter the details of sub directories:\n"); for(j=0;j<dir->nsd;j++)
{
dir->sub[j]=(struct directory *)malloc(sizeof(struct directory)); mkdir(dir->sub[j]);
}
printf("Enter the no.of files in the directory %s:",dir->name); scanf("%d",&dir->nf);
if(dir->nf!=0)
printf("Enter the file names:\n");

for(j=0;j<dir->nf;j++) scanf("%s",dir->file[j]);
}
void display(struct directory *dir,int i)
{
int j,x; for(x=0;x<i;x++)
printf("\t"); printf("%s\n",dir->name); for(j=0;j<dir->nsd;j++)
display(dir->sub[j],i+1); for(j=0;j<dir->nf;j++)
{
for(x=0;x<=i;x++) printf("\t");
printf("%s\n",dir->file[j]);
}
}
int main()
{
struct directory dir[50]; int n,i,j,k;
printf("Enter the no. of Directories:"); scanf("%d",&n);
for(i=0;i<n;i++)
mkdir(&dir[i]); printf("\nDirectory Structure..\n"); for(i=0;i<n;i++)
display(&dir[i],0); return 0;
}
OUTPUT:
Enter the no. of Directories:2 Enter the name of the Directory:
it
Enter the no.of sub directories in the directory it:2 Enter the details of sub directories:
Enter the name of the Directory:IIyear
Enter the no.of sub directories in the directory IIyear:2 Enter the details of sub directories:
Enter the name of the Directory:Subject
Enter the no.of sub directories in the directory Subject:0 Enter the no.of files in the directory Subject:5
Enter the file names:
PQT.txt DAA.txt OS.txt MPMC.txt SE.txt
Enter the name of the Directory:Staff
Enter the no.of sub directories in the directory Staff:0 Enter the no.of files in the directory Staff:1
Enter the file names:
staff.doc
Enter the no.of files in the directory IIyear:1 Enter the file names:
stud.doc
Enter the name of the Directory:IIIyear
Enter the no.of sub directories in the directory IIIyear:2 Enter the details of sub directories:
Enter the name of the Directory:Subject
Enter the no.of sub directories in the directory Subject:0 Enter the no.of files in the directory Subject:6
Enter the file names: NM.txt

NPM.txt CNS.txt ES.txt OOAD.txt WT.txt


Enter the name of the Directory:Staff
Enter the no.of sub directories in the directory Staff:0 Enter the no.of files in the directory Staff:1
Enter the file names:
staff.doc
Enter the no.of files in the directory IIIyear:1 Enter the file names:
stud.doc
Enter the no.of files in the directory it:2 Enter the file names:
markII.xls markIII.xls
Enter the name of the Directory:cse
Enter the no.of sub directories in the directory cse:1 Enter the details of sub directories:
Enter the name of the Directory:Staff
Enter the no.of sub directories in the directory Staff:0 Enter the no.of files in the directory Staff:1
Enter the file names:
staff.doc
Enter the no.of files in the directory cse:1 Enter the file names:
staff.xls

Directory Structure.. it
IIyear
Subject
PQT.txt
Staff
DAA.txt OS.txt MPMC.txt SE.txt
staff.doc
stud.doc IIIyear
Subject
NM.txt NPM.txt CNS.txt ES.txt OOAD.txt WT.txt
Staff
staff.doc
cse
stud.doc markII.xls markIII.xls
Staff
staff.doc staff.xls

Result:
Thus, the implementation of hierarchical level directory file organization technique is executed
successfully.

You might also like