0% found this document useful (0 votes)
7 views

Os Lab Record

The document provides a comprehensive overview of various UNIX commands, including their syntax and options for date, calendar, echo, and file manipulation commands. It also covers directory-related commands, VI editor commands, and shell programming commands. The aim is to educate users on executing and utilizing these commands effectively in a UNIX environment.

Uploaded by

examcell.vvcet
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)
7 views

Os Lab Record

The document provides a comprehensive overview of various UNIX commands, including their syntax and options for date, calendar, echo, and file manipulation commands. It also covers directory-related commands, VI editor commands, and shell programming commands. The aim is to educate users on executing and utilizing these commands effectively in a UNIX environment.

Uploaded by

examcell.vvcet
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/ 80

Ex.No : 1.

a UNIX COMMANDS

AIM :
To study and execute the commands in unix.

COMMAND :
1. Date:
This command is used to display the current data and time.
Syntax :
$date
$date +%ch
Options : -
a = Abbrevated
weekday. A = Full
weekday.
b = Abbrevated
month.B = Full
month.
c = Current day and time.
C = Display the century as a decimal
number.d = Day of the month.
D = Day in „mm/dd/yy‟
formath = Abbrevated month
day.
H = Display the
hour.L = Day of the
year.
m = Month of the
year.M = Minute.
P = Display AM or
PMS = Seconds
T = HH:MM:SS
formatu = Week of the
year.
y = Display the year in 2
digit.Y = Display the full
year.
Z = Time zone
.To change the format
:
Syntax :
$date ―+%H-%M-%S‖

2. Calender:
This command is used to display the calendar of the year or the particular month of calendar
year.
Syntax :
a. $cal <year>
b. $cal <month> <year>
Here the first syntax gives the entire calendar for given year & the second Syntax gives
thecalendar of reserved month of that year.
3. Echo:
This command is used to print the arguments on the screen .
Syntax : $echo <text>

Multi line echo:


To have the output in the same line , the following commands can be used.
Syntax : $echo <text\>text
To have the output in different line, the following command can be used.
Syntax : $echo ―text
>line2
>line3‖
4. Banner:
It is used to display the arguments in „#‟ symbol .
Syntax : $banner <arguments>

5. ’who’:
It is used to display who are the users connected to our computer currently.
Syntax : $who – option‟s
Options : -
H–Display the output with headers.
b–Display the last booting date or time or when the system was lastely rebooted.

6. ’who am i’:
Display the details of the current working directory.
Syntax : $who am i
7. ’tty’
It will display the terminal name.
Syntax : $tty
8. ’Binary’ Calculator:
It will change the „$‟ mode and in the new mode, arithematic operations such as +,-
,*,/,%,n,sqrt(),length(),=, etc can be performed . This command is used to go to the binary
calculusmode.
Syntax :
$bc operations
^d
$
1 base –inputbase
0 base – outputbase are used for base
conversions. Base :
Decimal = 1 Binary = 2 Octal = 8 Hexa = 16
9. ’CLEAR’:
It is used to clear the screen.
Syntax : $clear

10. ’MAN’:
It help us to know about the particular command and its options & working. It is like „help‟
command in windows .
Syntax : $man <command name>
11. MANIPULATION:
It is used to manipulate the screen.
Syntax : $tput <argument>
Arguments :
1. Clear – to clear the screen.
2. Longname – Display the complete name of the terminal.
3. SMSO – background become white and foreground become black
color.
4. 4.rmso – background become black and foreground becomes white
color.
5.Cop R C – Move to the cursor position to the specified
location.6.Cols – Display the number of columns in our
terminals.

12. LIST Command :


It is used to list all the contents in the current working directory.
Syntax : $ ls – options <arguments>
If the command does not contain any argument means it is working in the Current directory.
Options :
a– used to list all the files including the hidden
files.c– list all the files column wise.
d- list all the directories.
m- list the files separated by commas.
p- list files include „/‟ to all the
directories.r- list the files in reverse
alphabetical order.
f- list the files based on the list modification
date.x-list in column wise sorted order.

DIRECTORY RELATED COMMANDS :

1. Present Working Directory:


To print the complete path of the current working directory.
Syntax : $pwd

2. MKDIR:
To create or make a new directory in a current directory .
Syntax : $mkdir <directory name>

3. CD:
To change or move the directory to the mentioned directory .
Syntax : $cd <directory name.

4. RMDIR:
To remove a directory in the current directory & not the current directory itself.
Syntax : $rmdir <directory name>

FILE RELATED COMMANDS

:1.CREATE A FILE :
To create a new file in the current directory we use CAT command.
Syntax :
$cat > <filename.
The > symbol is redirectory we use cat command.
2. DISPLAY A FILE :
To display the content of file mentioned we use CAT command without „>‟ operator.
Syntax :
$cat <filename.
Options –s = to neglect the warning /error message.

3. COPYING CONTENTS :
To copy the content of one file with another. If file doesnot exist, a new file is created
and ifthe file exists with some data then it is overwritten.
Syntax :
$ cat <filename source> >> <destination filename>
$ cat <source filename> >> <destination filename> it is avoid overwriting.
Options : -
-n content of file with numbers included with blank lines.
Syntax :
$cat –n <filename>

4. SORTING A FILE :
To sort the contents in alphabetical order in reverse order.
Syntax :
$sort <filename >
Option : $ sort –r <filename>

5. COPYING CONTENTS FROM ONE FILE TO ANOTHER :


To copy the contents from source to destination file . so that both contents are same.

Syntax :
$cp <source filename> <destination filename>
$cp <source filename path > <destination filename path>

6. MOVE:
To completely move the contents from source file to destination file and to remove the source
file.
Syntax :
$ mv <source filename> <destination filename>
7. REMOVE:
To permanently remove the file we use this command .
Syntax :
$rm <filename>

8. WORD:
To list the content count of no of lines , words, characters .
Syntax :
$wc<filename>
Options :
-c – to display no of characters.
-l – to display only the lines.
-w – to display the no of words.

9. LINE PRINTER :
To print the line through the printer, we use lp command.
Syntax :
$lp <filename>

10. PAGE:
This command is used to display the contents of the file page wise & next page can be
viewedby pressing the enter key.
Syntax :
$pg <filename>

11. FILTERS AND PIPES


HEAD : It is used to display the top ten lines of file.
Syntax: $head<filename>
TAIL : This command is used to display the last ten lines of file.
Syntax: $tail<filename>
PAGE : This command shows the page by page a screenfull of information is displayed
after which the page command displays a prompt and passes for the user to strike the enter key to
continuescrolling.
Syntax: $ls –a\p
MORE : It also displays the file page by page .To continue scrolling with more
command ,press the space bar key.
Syntax: $more<filename>
GREP :This command is used to search and print the specified patterns from the file.
Syntax: $grep [option] pattern <filename>
SORT : This command is used to sort the datas in some order.
Syntax: $sort<filename>
PIPE : It is a mechanism by which the output of one command can be channeled into the
inputof another command.
Syntax: $who | wc-l
TR :The tr filter is used to translate one set of characters from the standard inputs to another.
Syntax: $tr ―[a-z]‖ ―[A-Z]‖

COMMUNICATION THROUGH UNIX COMMANDS


1. MESG
Description: The message command is used to give permission to other users to send
messageto your terminal.
Syntax: $mesg y

2. WRITE
Description: This command is used to communicate with other users, who are logged in at
thesame time.
Syntax: $write <user name>
3. WALL
Description: This command sends message to all users those who are logged in using the unix
server.
Syntax: $wall <message>
4. MAIL
Description: It refers to textual information, that can be transferred from one user to another
Syntax: $mail <user name>
5. REPLY
Description: It is used to send reply to specified user.
Syntax: $reply<user name>
EX.NO :1.b VI EDITOR COMMANDS

Aim :
To study the various commands operated in vi editor in UNIX.

Description :
The Vi editor is a visual editor used to create and edit text, files, documents and Programs. It
displays the content of files on the screen and allows a user to add, delete or change part of text . There
are three modesavailable in the Vi editor , they are
1. Command mode
2.Input (or) insert
mode.

Starting Vi :
The Vi editor is invoked by giving the following commands in UNIX prompt.
Syntax : $vi <filename> (or) $vi
This command would open a display screen with 25 lines and with tilt (~) symbol at the start of
eachline. The first syntax would save the file in the filename mentioned and for the next the filename
must be mentioned at the end.
Options :
1.vi +n <filename> - this would point at the nth line (cursor pos).
2.vi –n <filename> - This command is to make the file to read only to change from one mode
toanother press escape key.

INSERTING AND REPLACING COMMANDS :


To move editor from command node to edit mode, you have to press the <ESC> key. For inserting and
replacing the following commands are used.

1. ESC a:
This command is used to move the edit mode and start to append after the current character.
Syntax : <ESC> a

2. ESC A:
This command is also used to append the file , but this command append at the end of current line.
Syntax : <ESC> A

3. ESC i:
This command is used to insert the text before the current cursor position.
Syntax : <ESC> i
4. ESC I:
This command is used to insert at the beginning of the current line.
Syntax : <ESC> I
5. ESC o:
This command is insert a blank line below the current line & allow insertion of contents.
Syntax : <ESC> o
6. ESC O:
This command is used to insert a blank line above & allow insertion of contents.
Syntax : <ESC> O
7. ESC r:
This command is to replace the particular character with the given characters.
Syntax : <ESC> rx Where x is the new character.
8. ESC R:
This command is used to replace the particular text with a given text.
Syntax : <ESC> R text
9. <ESC> s:
This command replaces a single character with a group of character .
Syntax : <ESC> s
10. <ESC> S:
This command is used to replace a current line with group of characters.
Syntax : <ESC> S

CURSOR MOVEMENT IN vi :

1. <ESC> h :
This command is used to move to the previous character typed. It is used to move to left of the
text . Itcan also used to move character by character (or) a number of characters.
Syntax : <ESC> h – to move one character to left.
<ESC> nh – tomove „n‟ character to left.
2. <ESC> l :
This command is used to move to the right of the cursor (ie) to the next character. It can also be
usedto move the cursor for a number of character.
Syntax : <ESC> l – single character to right.
<ESC> nl - „n‟ characters to right.
3. <ESC> j :
This command is used to move down a single line or a number of lines.
Syntax : <ESC> j – single down movement.
<ESC> nj – „n‟ times down movement.
4. <ESC> k :
This command is used to move up a single line or a number of lines.
Syntax : <ESC> k – single line above.
<ESC> nk – „n‟ lines above.
5. ENTER (OR) N ENTER :
This command will move the cursor to the starting of next lines or a group of lines mentioned.
Syntax : <ESC> enter <ESC> n enter.
6.<ESC> +:
This command is used to move to the beginning of the next line.
Syntax : <ESC> + <ESC> n+
7.<ESC> -:
This command is used to move to the beginning of the previous line.
Syntax : <ESC> - <ESC> n-
8.<ESC> 0 :
This command will bring the cursor to the beginning of the same current line.
Syntax : <ESC> 0
9.<ESC> $ :
This command will bring the cursor to the end of the current line.
Syntax : <ESC> $
10.<ESC> ^ :
This command is used to move to first character of first lines.
Syntax : <ESC> ^
11. <ESC> b:
This command is used to move back to the previous word (or) a number of words.
Syntax : <ESC> b <ESC>nb
12. <ESC> e:
This command is used to move towards and replace the cursor at last character of the word (or) no of
words.
Syntax : <ESC> e <ESC>ne
13. <ESC> w Command :
This command is used to move forward by a single word or a group of words.
Syntax :
<ESC> w <ESC> nw

DELETING THE TEXT FROM Vi :


1. <ESC> x:
To delete a character to right of current cursor positions , this command is used.
Syntax :
<ESC> x <ESC> nx
2. <ESC> X:
To delete a character to left of current cursor positions , this command is used.
Syntax :
<ESC> X <ESC> nX
3. <ESC> dw:
This command is to delete a single word or number of words to right of current cursor position.
Syntax :
<ESC> dw <ESC> ndw
4. db Command :
This command is to delete a single word to the left of the current cursor position.
Syntax :
<ESC> db <ESC> ndb
5. <ESC> dd:
This command is used to delete the current line (or) a number of line below the current line.
Syntax :
<ESC> dd <ESC> ndd
6. <ESC> d$:
This command is used to delete the text from current cursor position to last character of current line.
Syntax : <ESC> d$

SAVING AND QUITING FROM vi


:-1.<ESC> w:
To save the given text present in the file.
Syntax : <ESC> : w
2. <ESC> q!:
To quit the given text without saving.
Syntax : <ESC> :q!
3. <ESC> wq:
This command quits the vi editor after saving the text in the mentioned file.
Syntax : <ESC> :wq
4. <ESC> x:
This command is same as „wq‟ command it saves and quit.
Syntax : <ESC> :x
5. <ESC> q:
This command would quit the window but it would ask for again to save the file.
Syntax : <ESC> : q
EX.NO :1.c UNIX SHELL PROGRAMMING COMMANDS

Aim :
To study about the Unix Shell Programming Commands.
Introduction :
Shell Programming is a group of commands grouped together under single filename. After
loggingonto the system a prompt for input appears which is generated by a Command String
Interpreter Program called the shell. The shell interprets the input, takes appropriate action, and
finally prompts for more input.The shell can be used either interactively - enter commands at the
command prompt, or as an interpreter to execute a shell script. Shell scripts are dynamically
interpreted, NOT compiled.
Common Shells.
 C-Shell - csh : The default on teaching systems Good for interactive systems Inferior
Programmablefeatures
 Bourne Shell - bsh or sh - also restricted shell - bsh : Sophisticated pattern matching and file
namesubstitution
 Korn Shell : Backwards compatible with Bourne Shell Regular expression substitution emacs
editingmode
 Thomas C-Shell - tcsh : Based on C-Shell Additional ability to use emacs to edit the command
lineWord completion & spelling correction Identifying your shell.
01. SHELL KEYWORDS :
echo, read, if fi, else, case, esac, for , while , do , done, until , set, unset, readonly, shift, export,
break, continue, exit, return, trap , wait, eval ,exec, ulimit , umask.
02. General things SHELL
The shbang line The "shbang" line is the very first line of the script and lets the kernel know what
shell will be interpreting the lines in the script. The shbang line consists of a #! followed by the full
pathname to the shell, and can be followed by options to control the behavior of the shell.
EXAMPLE
#!/bin/sh

Comments Comments are descriptive material preceded by a # sign. They are in effect until the end of
a line and can be started anywhere on the line.

EXAMPLE
# this text is not # interpreted by the shell
Wildcards There are some characters that are evaluated by the shell in a special way. They are called
shell metacharacters or "wildcards." These characters are neither numbers nor letters. For example, the *,
?, and [ ] areused for filename expansion. The <, >, 2>, >>, and | symbols are used for standard I/O
redirection and pipes. To prevent these characters from being interpreted by the shell they must be
quoted.

EXAMPLE
Filename expansion:
rm *; ls ??; cat file[1-3];
Quotes protect
metacharacter:
echo "How are you?"

03. SHELL VARIABLES :


Shell variables change during the execution of the Program .The C Shell offers a command
"Set" to assign a value to a variable.
For example:
% set myname= Fred
% set myname = "Fred Bloggs"
% set age=20
A $ sign operator is used to recall the variable values.
For example:
% echo $myname will display Fred Bloggs on the
screen A @ sign can be used to assign the integer constant
values.
For example:
%@myage=20
%@age1=10
%@age2=20
%@age=$age1+$age2
%echo $age

List variables
% set Programming_languages= (C LISP)
% echo $Programming _languages

C LISP
% set files=*.*
% set colors=(red blue green)
% echo $colors[2]

blue
% set colors=($colors yellow)/add to list

Local variables
Local variables are in scope for the current shell. When a script ends, they are no longer available;
i.e.,they go out of scope. Local variables are set and assigned values.
EXAMPLE
variable_name=value name="John Doe" x=5

Global variables
Global variables are called environment variables. They are set for the currently running shell
and anyprocess spawned from that shell. They go out of scope when the script ends.
EXAMPLE
VARIABLE_NAME=value export VARIABLE_NAME PATH=/bin:/usr/bin:. export PATH

Extracting values from variables To extract the value from variables, a dollar sign is used.

EXAMPLE
echo $variable_name echo $name echo $PATH
Rules : -
1.A variable name is any combination of alphabets, digits and an underscore („-„);
2.No commas or blanks are allowed within a variable name.
3.The first character of a variable name must either be an alphabet or an
underscore.4.Variables names should be of any reasonable length.
5.Variables name are case sensitive . That is , Name, NAME, name, NAme, are all different variables.
04. EXPRESSION Command :
To perform all arithematic operations .
Syntax :
Var = „expr$value1‟ + $ value2‟

Arithmetic
The Bourne shell does not support arithmetic. UNIX/Linux commands must be used to perform
calculations.
EXAMPLE
n=`expr 5 +
5`echo $n
Operators
The Bourne shell uses the built-in test command operators to test numbers and strings.
EXAMPLE
Equality:
= string
!= string
-eq number
-ne number
Logical:
-a and
-o or ! not
Logical:
AND
&&OR ||
Relational:
-gt greater than
-ge greater than, equal to
-lt less than
-le less than, equal to
Arithmetic :
+, -, \*, /, %
Arguments (positional parameters)
Arguments can be passed to a script from the command line. Positional parameters are used to
receive theirvalues from within the script.

EXAMPLE
At the command line:
$ scriptname arg1 arg2 arg3 ...
In a script:
echo $1 $2 $3 Positional parameters
echo $* All the positional paramters
echo $# The number of positional parameters
05.READ Statement :
To get the input from the user.
Syntax :
read x y
(no need of commas between variables)
06. ECHO Statement :
Similar to the output statement. To print output to the screen, the echo command is used.
Wildcards must be escaped with either a backslash or matching quotes.
Syntax :
Echo ―String‖ (or) echo $ b(for variable).
EXAMPLE
echo "What is your name?"

Reading user input The read command takes a line of input from the user and assigns it to a
variable(s) onthe right-hand side. The read command can accept muliple variable names. Each variable
will be assigned a word.

EXAMPLE
echo "What is your name?" read name read name1 name2 ...
6. CONDITIONAL STATEMENTS :
The if construct is followed by a command. If an expression is to be tested, it is enclosed
in squarebrackets. The then keyword is placed after the closing parenthesis. An if must end with a
fi.
Syntax :
1. if
This is used to check a condition and if it satisfies the condition if then does the
nextaction , if not it goes to the else part.
2. if…else
Syntax :
If cp $ source $
targetThen
Echo File copied
Else
successfullyEcho Failed to
3.nested if
copy the file.

here sequence of condition are checked and the corresponding performed accordingly.
Syntax :
if
condition
then
comman
d if
condition
then
comman
else
d
fi
4.case ….. fi comman
esac
d

This construct helps in execution of the shell script based on Choice.


EXAMPLE The if construct is: The case command construct
if is:
command case variable_name
then in pattern1)
block of statements statements
fi ;;
pattern2)
statement
if [ expression s
] then ;;
block of statements pattern3)
fi ;;
*) default value
The if/else/else if construct is: ;;
if esac
command case "$color"
then in blue)
block of echo $color is blue
statements elif ;;
command green)
then echo $color is green
block of ;;
statements elif
command
then
07. LOOPS
There are three types of loops: while, until and for. The while loop is followed by a
command or an expression enclosed in square brackets, a do keyword, a block of statements, and
terminated with the done keyword. As long as the expression is true, the body of statements
between do and done will be executed.
The until loop is just like the while loop, except the body of the loop will be executed as
long as the expression is false.
The for loop used to iterate through a list of words, processing a word and then shifting it off, to
process thenext word. When all words have been shifted from the list, it ends. The for loop is followed by
a variable name, the in keyword, and a list of words then a block of statements, and terminates with the
done keyword.
The loop control commands are break and continue.
EXAMPLE
while
command do
block of statements
done

while [ expression
] do
block of statements
done
until command for variable in word1 word2
word3 ...do
block of
statements done

until [ expression
] do
block of statements
done

until control
commanddo
commands
done

08. Break STATEMENT


This command is used to jump out of the loop instantly, without waiting to get the control command.

09. ARRAYS
(positional parameters) The Bourne shell does support an array, but a word list can be created by
using positional parameters. A list of words follows the built-in set command, and the words are accessed
by position. Up to nine positions are allowed.
The built-in shift command shifts off the first word on the left-hand side of the list. The
individual words are accessed by position values starting at 1.
EXAMPLE
set word1 word2 word3
echo $1 $2 $3 Displays word1, word2, and
word3set apples peaches plums
shift Shifts off apples
echo $1 Displays first element of the list
echo $2 Displays second element of the list echo
$* Displays all elements of the list
Command substitution
To assign the output of a UNIX/Linux command to a variable, or use the output of a command
in astring, backquotes are used.
EXAMPLE
variable_name=`comma
nd`echo $variable_name
now=`date`
echo $now
echo "Today is `date`"

10. FILE TESTING


The Bourne shell uses the test command to evaluate conditional expressions and has a built-in
set of options for testing attributes of files, such as whether it is a directory, a plain file (not a directory),
a readable file, and so forth.
EXAMPLE
-d File is a directory
-f File exists and is not a directory
–r Current user can read the file
–s File is of nonzero size
–w Current user can write to the file
–x Current user can execute the file
#!/bin/sh
1 if [ –f file
] then
echo file exists
fi
2 if [ –d file
] then
echo file is a directory
fi
3 if [ -s file
] then
echo file is not of zero length
fi
4 if [ -r file -a -w
file ] then
echo file is readable and writable
fi
11. EXECUTION OF SHELL
SCRIPT : 1.By using change
mode command 2.$ chmod u + x
sum.sh
3.$ sum.sh
or
$ sh sum.sh
EX.NO:2a PROCESS CREATION – FORK

Aim:
To write a program to create a process in UNIX.

Algorithm:
Step 1: Start the program.
Step 2: Declare pid as
integer.
Step 3: Create the process using Fork command.
Step 4: Check pid is less than 0 then print error else if pid is equal to 0 then execute command
elseparent process wait for child process.
Step 5: Stop the program.

Program:
#include<stdio.h>
#include<stdlib.h>void main()
{
int id;
id=fork();
if(id<0)
{
printf(―cannot create the file‖);
exit(-1);
}
if(id==0)
{
printf(―child
process‖); exit(0);
}
else
{
printf(―parent process‖);
}
}

Output:
[oslab@localhost oslab]$ cc
forkpg.c[oslab@localhost oslab]$
./a.out child processparent process

[oslab@localhost oslab]$ ps
PID TTY TIME
CMD
19193 pts/3 00:00:00 bash
19255 pts/3 00:00:00 ps
Ex.No: 2b EXECUTION COMMAND - EXEC

Aim:
To write a program for executing a command.
Algorithm:
Step 1: Start the program.
Step 2: Execute the command in the shell program using exec
ls.Step 3: Stop the execution.
Program:
echo Program for executing UNIX command using shell programming
echo Welcome
ps
exec wc e
Output:

[oslab@localhost oslab]$ cat >ehai

[oslab@localhost oslab]$ sh exec.sh


Program for executing UNIX command using shell
programmingWelcome
PID TTY TIME CMD
19193 pts/3 00:00:00 bash
19270 pts/3 00:00:00 sh
19271 pts/3 00:00:00 ps
1 1 4e
Ex.No:2c SLEEP COMMAND USING GETPID

Aim:
To create child with sleep command using getpid.
Algorithm:
Step 1: Start the execution and create a process using fork() command.
Step 2: Make the parent process to sleep for 10 seconds.
Step 3: In the child process print it pid and it corresponding
pid.Step 4: Make the child process to sleep for 5 seconds.
Step 5: Again print it pid and it parent pid.
Step 6: After making the sleep for the parent process for 10 seconds print it
pid.Step 7: Stop the execution.
Program:
void main()
{
int pid;
pid=fork()
;if
(pid==0)
{
printf(―\n Child Process\n‖);
printf(―\n Child Process id is %d ‖,getpid());
printf(―\n Its parent process id is %d‖,getppid());
sleep(5);
printf(―Child process after sleep=5\n‖);
printf(―\n Child Process id is %d ‖,getpid());
printf(―\n Its parent process id is %d‖,getppid());
}
else
{
printf(―\nParent
process‖); sleep(10);
printf(―\n Child Process id is %d ‖,getpid());
printf(―\n Its parent process id is %d‖,getppid());
printf(―\nParent terminates\n‖);
}
}
Output:
[oslab@localhost oslab]$ cc
getpid.c[oslab@localhost oslab]$
./a.out

Child Process
Child Process id is 19293
Its parent process id is 19292Child process after
sleep=5Child Process id is 19293
Its parent process id is 19292Parent process
Child Process id is 19292
Its parent process id is
19193Parent terminates
Ex.No:2d SIGNAL HANDLING -EXIT

Aim:
To write a program for signal handling in UNIX.
Algorithm:
Step 1:start the program
Step 2:Read the value of
pid.
Step 3:Kill the command surely using kill-9
pid.Step 4:Stop the program.
Program:
echo program for performing KILL
operationsps
echo enter the
pidread pid
kill $pid
echo
finished

Output:
[oslab@localhost oslab]$ sh exit.sh
program for performing KILL
operationsPID TTY TIME CMD
19193 pts/3 00:00:00 bash
19332 pts/3 00:00:00 sh
19333 pts/3 00:00:00
psenter the pid
19193
finished
Ex.No:2e WAIT COMMAND

Aim:
To perform wait command using c program.

Algorithm:
Step 1: Start the execution
Step 2: Create process using fork and assign it to a variable
Step 3: Check for the condition pid is equal to 0
Step 4: If it is true print the value of i and teriminate the child process
Step 5: If it is not a parent process has to wait until the child teriminate
Step 6: Stop the execution
Program:
#include<stdio.h>
int i=10;
void main()
{
int
pid=fork();
if(pid==0)
{
printf(―initial value of i %d \n ―,i); i+=10;
printf(―value of i %d \n ―,i);
printf(―child terminated \n‖);
}
else
{
wait(0);
printf(―value of i in parent process %d‖,i);
}
}
Output:
$cc wait.c
$a.out
initial value of i
10value of i 20
child teriminated
value of i in parent process 10$
Ex.No:2f OPENDIR, READDIR AND CLOSE COMMANDs

Aim:
To perform opendir, readdir and Close command using c program.
Algorithm:
Step 1: Start the execution
Step 2: Read the directory name, if not exist, display ―given directory does not exist‖
Step 3: otherwise, read the subdirectory and files using readdir command
Step 4: display the directory structure
Step 5: close the directirory usngi closedir command
Step 6: Stop the execution
Program:
#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc, char *argv[])
{
char buff[100];
DIR *dirp;
printf(―\n\n ENTER DIRECTORY NAME‖);
scanf(―%s‖, buff);
if((dirp=opendir(buff))==NULL)
{
printf(―The given directory does not exist‖);
exit(1);
}
while(dptr=readdir(dirp))
{
printf(―%s\n‖,dptr->d_name);
}
closedir(dirp);
}
Output:[oslab@localhost oslab]$ mkdir
mathi[oslab@localhost oslab]$ cd mathi
[oslab@localhost mathi]$ cat >test
hai
welcome
[oslab@localhost mathi]$ cat >test1.doc
this is OS Lab
[oslab@localhost mathi]$ ls
test test1.doc
[oslab@localhost mathi]$cd\
[oslab@localhost oslab]$ cc opredir.c
[oslab@localhost oslab]$ ./a.out
ENTER DIRECTORY NAME mathi
.
..
test
test1.doc
Ex.No:2g STAT COMMAND

Aim:
To perform stat command using c program.

Algorithm:
Step 1: Start the execution
Step 2: Read file name as command line argument
Step 3: Display the file status information like size, link, inode, permissions, etc., using fileStat
varibleStep 4: Stop the execution

Program:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
if(argc != 2)
return 1;
if(stat(argv[1],&fileStat) < 0)
return 1;

printf("Information for %s\n",argv[1]);


printf(" \n");
printf("File Size: \t\t%d bytes\n",fileStat.st_size);
printf("Number of Links: \t%d\n",fileStat.st_nlink);
printf("File inode: \t\t%d\n",fileStat.st_ino);
printf("File Permissions: \t");
printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");
printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");
printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");
printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");
printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");
printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");
printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");
printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");
printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");
printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");
printf("\n\n");
printf("The file %s a symbolic link\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");
return 0;
}
Input:
[oslab@localhost oslab]$ cc stat.c
[oslab@localhost oslab]$ ./a.out forkpg.c

Output:
Information for forkpg.c

File Size: 231 bytes


Number of Links: 1
File inode: 64718
File Permissions: -rw-rw-r--

The file is not a symbolic link


Ex. No:3a) CP COMMAND

Aim:
To write a C Program to simulate the operation of ―cp‖ command in Unix.

Algorithm:
Step 1: Define the bufsize
Step 2: if argc!=3, display "Usage: cp "
Step 3: open the file specified in argv[1];
Step 4: if not specified, print "Unable to open file name‖
Step 5: read the content for file (argv[1]) and write it into another file specified in argv[2]
Step 6: Close files

Program:
#include "syscall.h"
#include "stdio.h"
#include "stdlib.h"
#define BUFSIZE 1024
char buf[BUFSIZE];
int main(int argc, char** argv)
{ int src, dst, amount;
if (argc!=3)
{
printf("Usage: cp \n");
return 1;
}
src = open(argv[1]);
if (src==-1)
{
printf("Unable to open %s\n", argv[1]);
return 1;
}
creat(argv[2]);
dst = open(argv[2]);
if (dst==-1)
{
printf("Unable to create %s\n", argv[2]);
return 1;
}
while ((amount = read(src, buf, BUFSIZE))>0)
{
write(dst, buf, amount);}
close(src);
close(dst);
return 0;
}
Input:
$ vi prg10.c
$ cc prg10.c
./a.out sampletext2 file10
Output:
Data copied from sampletext2 to file10
Ex. No:3b) LS COMMAND

Aim:
To write a C Program to simulate the operation of ―ls‖ command in Unix.
Algorithm:
1. Check if the number of command line arguments is less than
2. If yes, Print error and exit.
3. Check if the second argument (i.e. directory to be listed) is valid or not. If not then exit.
4. Print the content of the directory till it becomes NULL.
5. Close the directory entry file.
Program:
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h> main(int
argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc<2)
{
printf("\n You have provided only 1 argument\n");
exit(1);
}
if((dp=opendir(argv[1]))==NULL)
{
printf("\nCannot open %s file!\n",argv[1]);
exit(1);
}
while((dirp=readdir(dp))!=NULL)
printf("%s\n",dirp->d_name);
closedir(dp);
}
Output:
$gcc lsdemo.c
$./a.out
You have provided only 1 argument
$ ./a.out /xyz/foo
Cannot open /xyz/foo file!
$./a.out /root
$./a.out /tmp/orbit
.
..
first.c
best.c
a.out
lsdemo.
c
roundrobin.c
firstfit.c
roundrobin.do
c
Ex. No:3c) GREP COMMAND

Aim:
To write a C Program to simulate the operation of ―grep‖ command in Unix.

Algorithm:
1. Declare the file pointer.
2. Read the file and pattern to be applied ( -i text) te execute grep command
3. Open the input file in read mode and compare the input with the file content
4. Print the content which are present in the file till it becomes NULL.
5. Close the file.

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("Enter file name\n");
scanf("%s",fn);
printf("Enter pattern to be searched\n");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
printf("%s",temp);
}
fclose(fp);
}
Input:
$vi hello
Hello
Welcome
to OS
Laborator
y
$cc greppg.c
$./a.out
Enter file name
Hello
Enter pattern to be searched
to
Output:
to OS
Laboratory
EX.NO.4a) FIBONACCI SERIES

Aim:
To write a shell Program to generate the first n terms of the Fibonacci series.
Algorithm:
1. Read the no. of terms to be generated for Fibonacci series.
2. Initialize the first two elements as a=0 and b=1.
3. The next element will be generated each time based on sum of the previous two elements
i.e. C= a+b
4. Interchange the values of a and b.
5. Until, all the terms gets generated repeat Steps 3 and 4.
6. Print the first n terms of Fibonacci series.
Program:
#Fibonacci series
echo "Enter no. of terms to be generated for fibonacci series:"
read n
i=3
a=0
b=1
echo "The first $n terms of fibonacci series are : "
echo "$a"
echo "$b"
while [ $i -le $n ]
do
c=`expr $a + $b`
echo "$c"
a=$b
b=$c
i=`expr $i + 1`
done

Input:
$ sh fib.sh
Enter no. of terms to be generated for fibonacci series: 10
Output:
The first 10 terms of fibonacci series
are : 0
1
1
2
3
5
8
13
21
34
EX.NO.4b ARMSTRONG NUMBER CHECKING

Aim:
To write a shell Program for Armstrong number checking.
Algorithm:
1. Read any number.
2. Extract each digit of the number and find its cube value.
3. Until the number becomes zero, repeat Step 2.
4. Find the sum of cube values of each digit.
5. If the sum is equal to the given number then given no. is an Armstrong number.
Program:
#Armstrong number checking
echo "Enter any 3 digit no."
read n
z=$n
m=0
y=0
k=0
x=0
while [ $n -gt 0 ]
do
k=`expr $n % 10`
#k=`expr $k % $i`
x=`expr $k \* $k \* $k`
y=`expr $y + $x`
n=`expr $n / 10`
done
if [ $z -eq $y ]
then
echo "Given no $z is an armstrong no."
else
echo "Given no. $z is not an armstrong no."
fi

Input:
$ sh arm.sh
Enter any 3 digit
no.
153
Output:
Given no 153 is an armstrong no.
Input:
$ sh arm.sh
Enter any 3 digit
no.
122
Output:
Given no. 122 is not an armstrong no.
EX.NO.4c) PALINDROME CHECKING

Aim:
To write a shell program for palindrome checking.

Algorithm:
1. Read any string.
2. Find the length of given string.
3. Extract each character from string, starting from the last character and concatenate it to another
string.
4. Repeat Step 3 until the first character is reached.
5. If the new reversed string is equal to given string then it‘s a palindrome.

Program:
#Palindrome checking
n=0
echo -n "Enter any string: "
read str
len=`echo $str | wc -c`
while [ $len -gt $n ]
do
tem=`echo $str|cut -c $len`
rev=`echo $rev$tem`
len=`expr $len - 1`
done
if [ $str == $rev ]
then
echo "Given String is a palindrome"
else
echo "Given string is not a palindrome"
fi

Input:
$ sh palin.sh
Enter any string: malayalam
$ sh palin.sh
Enter any string: hello

Output:
Given String is a palindrome
Given string is not a
palindrome
EX.NO.4d) COUNT A NUMBER OF VOWELS IN GIVEN STRING

Aim:
To write a shell Program to count number of vowels in given string
Algorithm:
1. Read any string.
2. Find the length of the string and initialize the count by zero.
3. Extract each character from string &check if it‘s a vowel (ie. a,e,i,o,u)then increment the count by one.
4. Repeat Step 3 until last character of string is reached.
5. Display the value of count which indicates the number of vowels in string.
Program:
echo "Enter any string:"
read str
len=`echo $str | wc -c`
len=`expr $len - 1`
v=0
i=1
while [ $len -gt 0 ]
do
t=`echo $str | cut -c $len`
if [ $t = a ]
then
v=`expr $v + 1`
elif [ $t = e ]
then
v=`expr $v + $i`
elif [ $t = i ]
then
v=`expr $v + $i`
elif [ $t = o ]
then
v=`expr $v + $i`
elif [ $t = u ]
then
v=`expr $v + $i`
fi
len=`expr $len – 1`
done
echo ―No. of vowels present in string $str = $v‖
Input:
$ sh vowel.sh
Enter any
string:
dhanamathi
$ sh vowel.sh
Enter any
string:
hello
Output:
No. of vowels present in string dhanamathi = 4
No. of vowels present in string hello = 2
EX.NO.4e) ARITHMETIC CALCULATOR

Aim:
To write a shell Program to design an arithmetic calculator

Algorithm:
1. Start the Program
2. Display the menu as follows
1. Addition
2. Subtraction
3. Multiplication
4. Division
3. Get the user choice as ch
4. Perform the arithmetic operation as per the user choice
Stop the Program
Program
echo Enter any two numbers
read a b
echo Menu
echo 1.Addition
echo 2.Subtraction
echo 3.Muliplication
echo 4.Division
echo Enter your choice[1 - 4] :
read ch
case $ch in
1) echo The sum is $(($a + $b));;
2) echo The difference is $(($a - $b));;
3) echo The multiplication is $(($a * $b));;
4) echo The division is $(($a / $b));;
*) echo Wrong choice;;
esac
Input:
$ sh calculator.sh
Enter any two numbers 40 10
Menu
1.Addition
2.Subtraction
3.Muliplication
4.Division
Enter your choice[1 - 4]
1

Output:
The sum is 60
EX.NO.4f) BIGGEST AMONG THREE NUMBERS

Aim:
To write a shell Program to find the biggest among three numbers
Algorithm:
1. Start the Program
2. Get the numbers as num1, num2 and num3
3. check if num1 is greater than num2 and num3, if yes display num1 is the biggest number
4. Else check num2 is greater than num3, if yes display num2 is the biggest number
5. Else display num3 is the biggest number
6. Stop the Program

Program:
echo "Enter the First number"
read num1
echo "Enter the Second number"
read num2
echo "Enter the Third number"
read num3
if test $num1 -gt $num2 -a $num1 -gt $num3
then
echo "$num1 is a biggest number"
else
if test $num2 -gt $num3
then
echo "$num2 is a biggest number"
else
echo "$num3 is a biggest number"
fi
fi
Input:
$ sh big.sh
Enter the First number
10
Enter the Second number
60
Enter the Third number
30

Output:
60 is a biggest number
EX.NO.5a) FCFS SCHEDULING ALGORITHM

Aim
To write a C Program to implement FCFS scheduling algorithm.

Algorithm:
1. Read no. of processes.
2. Read process name and burst time for each process.
3. CPU schedules processes according to their order of arrival in read queue (ie It first executes
process which is at head of ready queue)
4. Set waiting time (WT) of first process as zero and turnaround time(TAT) as burst time.
5. Calculate waiting time and turnaround time of other processes as follows:
Pi (WT) = P i-1(WT) +P i-1(BT)
P i (TAT) = P i ( BT) + P i (WT)
6. Calculate and display average WT and TAT.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char pn[10][10];
int arr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,n;
int totwt=0,tottat=0;
clrscr();
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Process Name, Arrival Time & Burst Time:");
scanf("%s%d%d",&pn[i],&arr[i],&bur[i]);
}
for(i=0;i<n;i++)
{
if(i==0)
{
star[i]=arr[i];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
else
{
star[i]=finish[i-1];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
}
printf("\nPName Arrtime Burtime Start TAT Finish");
for(i=0;i<n;i++)
{
printf("\n%s\t%6d\t\t%6d\t%6d\t%6d\t%6d",pn[i],arr[i],bur[i],star[i],tat[i],finish[i]);
totwt+=wt[i];
tottat+=tat[i];
}
printf("\nAverage Waiting time:%f",(float)totwt/n);
printf("\nAverage Turn Around Time:%f",(float)tottat/n);
getch();
}

Input:
Enter the number of processes --3
Enter Burst Time for Process 0 --24
Enter Burst Time for Process 1 --3
Enter Burst Time for Process 2 --3

Output:

PROCESS BURST TIME WAITING TIME TURNAROUND TIME


P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time--17.000000
Average Turnaround Time--27.000000
EX.NO.5 b) SJF SCHEDULING ALGORITHM

Aim:
To write a C Program to implement SJF (Shortest Job First) scheduling algorithm.

Algorithm:
1. Read no. of processes.
2. Read process name and burst time for each process.
3. Sort the processes in ready queue according to burst time.CPU schedules process with shortest burst
time first followed by other processes.
4. Set waiting time(WT) of first process as zero and turnaround time(TAT) as burst time.
5. Calculate waiting time and turnaround time of other processes as follows:
Pi (WT) = P i-1(WT) +P i-1(BT)
P i (TAT) = P i ( BT) + P i (WT)
6. Calculate and display average WT and TAT.
7. Display order of execution of processes ie. Process name, burst time, WT and TAT.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10];
int totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process name, arrival time & execution time:");
flushall();
scanf("%s%d%d",pn[i],&at[i],&et[i]);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(et[i]<et[j])
{
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0;i<n;i++)
{
if(i==0)
st[i]=at[i];
else
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime");
for(i=0;i<n;i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}

Input:
Enter the number of processes --4
Enter Burst Timefor Process 0 --6
Enter Burst Time for Process 1 --8
Enter Burst Time for Process 2 --7
Enter Burst Time for Process 3 --3

Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
P3 3 0 3
P0 6 3 9
P2 7 9 16
P1 8 16 24
Average Waiting Time --7.000000
Average Turnaround Time --13.000000
EX.NO.5c) PRIORITY SCHEDULING ALGORITHM

Aim:
To implement a Program to simulate the priority CPU scheduling algorithm
Algorithm:
1. Read no. of processes.
2. Read process name, burst time and priority for each process.
3. Sort the processes in ready queue according to priority. (i.e. Process with high priority get placed at
head of ready queue) CPU schedules process with high priority first followed by other processes.
4. Set waiting time (WT) of first process as zero and turnaround time (TAT) as burst time.
5. Calculate waiting time and turnaround time of other processes as follows:
Pi (WT) = P i-1(WT) +P i-1(BT)
P i (TAT) = P i (BT) + P i (WT)
6. Calculate and display average WT and TAT.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int et[20],at[10],n,i,j,temp,p[10],st[10],ft[10],wt[10],ta[10];
int totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process name,arrivaltime,execution time & priority:");
flushall();
scanf("%s%d%d%d",pn[i],&at[i],&et[i],&p[i]);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(p[i]<p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0;i<n;i++)
{
if(i==0)
{
st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime");
for(i=0;i<n;i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],p[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}

Input:
Enter the number of processes –5
Enter the Burst Time & Priority of Process 0 ---10 3
Enter the Burst Time & Priority of Process 1 ---1 1
Enter the Burst Time & Priority of Process 2 ---2 4
Enter the Burst Time & Priority of Process 3 ---1 5
Enter the Burst Time & Priority of Process 4 ---5 2

Output:
PROCESS PRIORITY BURST TIMEWAITING TIME TURNAROUND TIME
1 1 1 0 1
4 2 5 1 6
0 3 10 6 16

Average Waiting Time is---8.200000


Average Turnaround Time is ---12.000000
EX.NO.5d) ROUND ROBIN SCHEDULING ALGORITHM

Aim
To write a C Program to implement round robin scheduling algorithm.

Algorithm:
1. Read no. of processes and time quantum( TQ).
2. Read process name and burst time(BT) for each process.
3. Ready queue is treated as circular queue.CPU schedules all processes (according to their of order of
arrival) only up to given time quantum.
4. A timer is set to interrupt the scheduling if time quantum expires for a process.
5. If BT of process is greater than TQ then after executing upto TQ, it gets added to tail of ready
queue.
6. If BT of process is less than TQ then CPU gets released from it and schedules next process in ready
queue.
7. Set waiting time (WT) of first process as zero and turnaround time(TAT) as burst time.
8. Calculate waiting time and turnaround time of other processes as follows:
Pi (WT) = P i-1(WT) +P i-1(BT)
P i (TAT) = P i (BT) + P i (WT)
9. Calculate and display average WT and TAT.
10. Display order of execution of processes ie. Process name, burst time, WT and TAT.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int et[30],ts,n,i,x=0,tot=0;
char pn[10][10];
clrscr();
printf("Enter the no of processes:");
scanf("%d",&n);
printf("Enter the time quantum:");
scanf("%d",&ts);
for(i=0;i<n;i++)
{
printf("enter process name & estimated time:");
scanf("%s %d",pn[i],&et[i]);
}
printf("The processes are:");
for(i=0;i<n;i++)
printf("process %d: %s\n",i+1,pn[i]);
for(i=0;i<n;i++)
tot=tot+et[i];
while(x!=tot)
{
for(i=0;i<n;i++)
{
if(et[i]>ts)
{
x=x+ts;
printf("\n %s -> %d",pn[i],ts);

et[i]=et[i]-ts;
}

else
if((et[i]<=ts)&&et[i]!=0)
{
x=x+et[i];
printf("\n %s -> %d",pn[i],et[i]);
et[i]=0;}
}}
printf("\n Total Estimated Time:%d",x);getch();}

Input:
Enter the no of processes –3
Enter Burst Time for process 1 –24
Enter Burst Time for process 2 --3
Enter Burst Time for process 3 --3
Enter the size of time slice –3

Output:
The Average Turnaround time is –15.666667
The Average Waiting time is --5.666667
PROCESS BURST TIMEWAITING TIME TURNAROUND TIME
1 24 6 30
2 3 4 7
3 3 7 10
EX.NO.6 SEMAPHORES

Aim:
To write a C Program to implement PCP (Producer Consumer Problem) using semaphores.

Algorithm:
1. Read size of buffer
2. Producer process produces and buffers the items using semget() and semctl()
3. Consumer process consumes item from buffer using semacq() and semrel()
4. Producer process waits if buffer is full and consumer process waits if buffer is empty.

Program:
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define NBUFF 10
int nitems;
struct{
int buff[NBUFF];
sem_t mutex,nempty,nstored;
}shared;
void *produce(void*);
void *consume(void*);
int main(int argc,char**argv)
{
pthread_t tid_produce,tid_consume;
if(argc!=2)
{
printf("usage:filename<nitems>");
return 0;
}
printf("\n\nproducer_consumer problem using semaphore \n");
printf(" ...................................................................................... \n");
nitems=atoi(argv[1]);
sem_init(&share d.mutex,0,1);
sem_init(&shared.nempty,0,NBUFF);
sem_init(&shared.nstored,0,0);
pthread_setconcurrency(2);
pthread_create(&tid_produce,NULL,produce,NULL);
pthread_create(&tid_consume,NULL,consume,NULL);
pthread_join(tid_produce,NULL);
pthread_join(tid_consume,NULL);
sem_destroy(&shared.mutex);
sem_destroy(&shared.nempty);
sem_destroy(&shared.nstored);
}
void *produce(void *arg)
{
int i;
for(i=0;i<nitems;i++)
{
sem_wait(&shared.nempty);
sem_wait(&shared.mutex);
shared.buff[i%NBUFF]=i;
printf("\ tproducer........");
printf("buff[%d]=%d\n\ n",i,shared.buff[i%NBUFF]);sem_post(&shared.mutex);
sem_post(&shared.nstored);
sleep(3);
}
return NULL;
}
void *consume(void *arg)
{
int i;
for(i=0;i<nitems;i++)
{
sem_wait(&shared.nstored);
sem_wait(&shared.mutex);
printf("\ tconsumer. ");
printf("buff[%d]=%d\n\n\n",i,shared.buff[i%NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nempty);
sleep(3);
}
return NULL;
}
Input:
Producer Consumer Problem using Semaphore
Enter the size for buffer 3
Output:
Item produced : 10
Item consumed:10
Item produced : 20
Item consumed:20
Item produced : 30
Item consumed:30
EX.NO.7 Implementation of Bankers Algorithm for Deadlock Avoidance

Aim:
To write a program to simulate the Bankers Algorithm for Deadlock Avoidance.
Algorithm:
Step1: Start the Program.
Step2: Get the values of resources and processes.
Step3: Get the avail value.
Step4: After allocation find the need value.
Step5: Check whether its possible to allocate.
Step6: If it is possible then the system is in safe state.
Step7: Else system is not in safety state.
Step8: If the new request comes then check that the system is in safety.
Step9: or not if we allow the request.
Step10: stop the Program. Step11: end

Program:
//Bankers algorithm for deadlock avoidance.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];
int p, r, i, j, process, count;
count = 0;

printf("Enter the no of processes : ");


scanf("%d", &p);

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


completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);

printf("\n\nEnter the Max Matrix for each process : ");


for(i = 0; i < p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}

printf("\n\nEnter the allocation for each process : ");


for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);

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

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


need[i][j] = Max[i][j] - alloc[i][j];

do
{
printf("\n Max matrix:\tAllocation matrix:\n");

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


{
for( j = 0; j < r; j++)
printf("%d ", Max[i][j]);
printf("\t\t");
for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]);
printf("\n");
}

process = -1;

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


{
if(completed[i] == 0)//if not completed
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1;
break;
}
}
}
if(process != -1)
break;
}

if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != p && process != -1);

if(count == p)
{
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!");

}
Input:
[root@comps 111a1059]# gcc bankerssafesequence.c
[root@comps 111a1059]# ./a.out
Enter the no of processes : 5
Enter the no of resources : 3
Enter the Max Matrix for each process :
For process 1 : 753
For process 2 : 322
For process 3 : 702
For process 4 : 222
For process 5 : 433
Enter the allocation for each process :
For process 1 : 010
For process 2 : 200
For process 3 : 302
For process 4 : 211
For process 5 : 002
Enter the Available Resources : 332

Output:
Max matrix: Allocation matrix:
753 010
322 200
702 302
222 211
433 002

Process 2 runs to completion!


Max matrix: Allocation matrix:
753 010
000 000
702 302
222 211
433 002

Process 3 runs to completion!


Max matrix: Allocation matrix:
753 010
000 000
000 000
222 211
433 002
Process 4 runs to completion!
Max matrix: Allocation matrix:
753 010
000 000
000 000
000 000
433 002
Process 1 runs to completion!
Max matrix: Allocation matrix:
000 000
000 000
000 000
000 000
433 002

Process 5 runs to completion!


The system is in a safe state!!
Safe Sequence : < 2 3 4 1 5 >
EX.NO.8 DEADLOCK DETECTION

Aim:
Develop a program to simulate the Bankers Algorithm for Deadlock detection
Algorithm:
Step1: Start the Program.
Step2: Get the values of resources and processes.
Step3: Get the avail value.
Step4: After allocation find the need value.
Step5: Check whether its possible to allocate.
Step6: If it is possible then the system is in safe state.
Step7: Else system is not in safety state
Step8: Stop the process.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int work[5],avl[5],alloc[10][10],l;
int need[10][10],n,m,I,j,avail[10],max[10][10],k,count,fcount=0,pr[10];
char finish[10]={‗f‘,‘f‘,‗f‘,‘f‘,‗f‘,‘f‘,‗f‘,‘f‘,‗f‘,‘f‘};
clrscr();
printf(―\n enter the no of process‖);
scanf(―%d‖,&n);
printf(―\n enter the no of resources‖);
scanf(―%d‖,&m);
printf(―\n enter the total no of resources‖);
for(i=1;i<=m;i++)
scanf(―%d‖,&avail[i]);
printf(―\n enter the max resources req by each pr alloc matrix‖);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf(―%d‖,&max[i][j]);
printf(―\n process allocation matrix‖);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf(―%d‖,&alloc[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
need[i][j]=max[i][j]-alloc[i][j];
for(i=1;i<=n;i++)
{
k=0;
for(j=1;j<=m;j++)
{
k=k+alloc[i][j];
}
avl[i]=avl[i]-k;
work[i]=avl[i];
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
{
count=0;
for(j=1;j<=m;j++)
{
if((finish[i]==‘f‘)&&(need[i][j]<=work[i]))
count++;
}
if(count==m)
{
for(l=1;l<=m;l++)
work[l]=work[l]+alloc[i][l];
finish[i]=‘t‘;
pr[k]=i;
break;
}
}
for(i=1;i<=n;i++)
if(finish[i]==‘t‘)
fcount++;
if(fcount==n)
{
printf(―\n the system is in safe state‖);
for(i=1;i<=n;i++)
printf(―\n %d‖,pr[i]);
}
Else
printf(―\n the system is not in safe state‖);
}

Input:
Enter the no of process 5
Enter the no of resources 3
Enter the total no of resources 10 5 7
Enter the max resource req. by each pr alloc matrix
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
Output:
Process allocation matrix
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
The system is in safe state 1 3 4 5 2
EX.NO.9 IMPLEMENTATION OF THREADING AND SYNCHRONIZATION

Aim:
To write a Program to implement synchronization in threading.

Algorithm:
Step1: Thread synchronization is defined as a mechanism which ensures that two or more
concurrent processes or threads do not simultaneously execute some particular program
segment known as critical section.
Step 2: Threads can be created using pthread_create() with the following prototype:
Creating a Thread ( pthread_create )
pthread_create is the function of pthread.h header file, which is used to create a thread.
The syntax and parametersdetails are given as follows:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void
*), void *arg);
pthread_t *thread
It is the pointer to a pthread_t variable which is used to store thread id of
new created thread. const pthread_attr_t *attr
It is the pointer to a thread attribute object which is used to set thread attributes,
NULL can be used to create athread with default arguments.
Step 3: When First thread starts, lock the section using pthread_mutex_lock(&lock)
Step 4: If the thread completes its process, unlock the section using
pthread_mutex_unlock(&lock)
Step 5: Allow next thread thread to execute.
Step 6: Continue the process till the last thread.
Program:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

pthread_t tid[2];
int counter;
pthread_mutex_t
lock; void*
trythis(void *arg)
{
pthread_mutex_lock(&lock);
unsigned long i = 0;
counter += 1;
printf("\n Job %d has started\n",
counter); for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d has finished\n", counter);
pthread_mutex_unlock(&lock);
return NULL;
}

int main(void)
{
int i =
0; int
error;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}
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);
pthread_mutex_destroy(&lock);
return 0;
}

Input:
[oslab@localhost oslab]$ cc thread1.c -lpthread
[oslab@localhost oslab]$ ./a.out
Output:
Job 1 has started

Job 1 has finished

Job 2 has started

Job 2 has finished


Ex.No. 10a) FIRST-FIT

Aim:
To write a Program to implement first-fit memory allocation method
Algorithm:
Step1: Declare the necessary variables
Step2: Read the number of blocks and files
Step3: Read the size of the file
Step4: Choose the block which is lage enough to fit the file, continue the process to fit all files into the
block
Stpe 5: display the allocation details and stop execution
Program:
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i); scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j; break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
printf("\nFile_no:\tFile_size
:\tBlock_no:\tBlock_size:\tFragement"); for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

Input:
Memory Management Scheme - First
Fit Enter the number of blocks: 3
Enter the number of files:
2 Enter the size of the
blocks:-Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the
files:-File 1: 1
File 2: 4
Output:
File No File Size Block No Block Size Fragmen
t
1 1 1 5 4
2 4 3 7 3
Ex.No. 10b) WORST-FIT
Aim:
To write a Program to implement worst-fit memory allocation method

Algorithm:
Step1: Declare the necessary variables
Step2: Read the number of blocks and files
Step3: Read the size of the file
Step4: Choose the block which is lagest to fit the file, choose the second largest block to fit
next file, continue the process to fit all files into the block
Stpe 5: Display the allocation details and stop execution

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

Input:
Memory Management Scheme – Best Fit
Enter the number of
blocks: 3Enter the number
of files: 2 Enter the size of
the blocks:- Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the
files:-File 1: 1
File 2: 4

Output:
File No File Size Block No Block Size Fragmen
t
1 1 3 7 6
2 4 1 5 1
Ex.No. 10c) BEST FIT

Aim:
To write a Program to implement Best-fit memory allocation method

Algorithm:
Step1: Declare the necessary variables
Step2: Read the number of blocks and
filesStep3: Read the size of the file
Step4: Choose the block which is closest in size to fit the file, choose the second closest in size
block to fit next file, continue the process to fit all files into the block
Stpe 5: Display the allocation details and stop execution

Program:
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
printf("\n\tMemory Management Scheme – Best Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i); scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;
lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment");
for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

Input:

Memory Management Scheme - Best


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

Enter the size of the


blocks:-Block 1:5
Block 2:2
Block 3:7
Enter the size of the files
:-File 1:1
File 2:4

Output:
File File Block No Block Size Fragmen
No Size t
1 1 2 2 1
2 4 1 5 1
EX. NO. 11 PAGING TECHNIQUE

Aim:
To write a C program for paging technique.
Algorithm:
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following Physical address = ( Frame number *
Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;
int s[10], fno[10][20];
clrscr();
printf("\nEnter the memory size --");
scanf("%d",&ms);
printf("\nEnter the page size --");
scanf("%d",&ps);
nop = ms/ps;printf("\nThe no. of pages available in memory are --%d ",nop);
printf("\nEnter number of processes --");
scanf("%d",&np);
rempages = nop;
for(i=1;i<=np;i++)
{
printf("\nEnter no. of pages required for p[%d]--",i);
scanf("%d",&s[i]);
if(s[i] >rempages)
{
printf("\nMemory is Full");
break;
}
rempages = rempages -s[i];
printf("\nEnter pagetable for p[%d] ---",i);
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnter Logical Address to find Physical Address ");
printf("\nEnter process no. and pagenumber and offset --");
scanf("%d %d %d",&x,&y, &offset);
if(x>np || y>=s[i] || offset>=ps)
printf("\nInvalid Process or Page Number or offset");
else
{
pa=fno[x][y]*ps+offset;
printf("\nThe Physical Address is --%d",pa);
}
getch();
}
Input:
Enter the memory size –1000
Enter the page size --100
The no. of pages available in memory are --10
Enter number of processes --3
Enter no. of pages required for p[1]--4
Enter pagetable for p[1] ---8 6 9 5
Enter no. of pages required for p[2]--5
Enter pagetable for p[2] ---1 4 5 7 3
Enter no. of pages required for p[3]--5

Output:
Memory is Full
Enter Logical Address to find Physical Address
Enter process no. and pagenumber and offset --2360
The Physical Address is --760
EX. NO. 12a) FIFO PAGE REPLACEMENT ALGORITHM

Aim:
To implement FIFO page replacement technique.
Algorithm:
Step1: Start the process
Step2: Read number of pages n
Step3: Read number of pages no
Step4: Read page numbers into an array a[i]
Step5: Initialize avail[i]=0 .to check page hit
Step6: Replace the page with circular queue, while re-placeing check page availability in the
frame Place avail[i]=1 if page is placed in the frame Count page faults
Step7: Print the results. Step8: Stop the process.
Program:
#include <stdio.h>
#include <conio.h>
int refstr[50],cq[10];
int f=0,r=0,pf=0,nof,len;
main()
{
int temp,i,count,p,f1;
int check(int);
void addq(int);
printf("\n\n\tFIFO PAGE REPLACEMENT ALGORITHM\n\n");
printf("Enter the no of frames\n");
scanf("%d",&nof);
printf("\nEnter the number of elements\n");
scanf("%d",&len);
for(count=0;count<nof;count++)
cq[count]=-1;
printf("\nEnter the elements\n");
for(i=0;i<len;i++)
scanf("%d",&refstr[i]);
count=0;
printf("\n\tCONTENTS OF FRAMES DURING PROCESSING\n\n");
for(i=0;i<nof;i++)
printf("F[%d]\t",i);
printf("Page fault\n");
do
{
p=refstr[count];
f1=check(p);
if(f1==0)
{
addq(p);
pf+=1;
}
count+=1;
for(i=0;i<nof;i++)
printf("%d\t",cq[i]);
if(f1==0)
printf("*\n");
else
printf("-\n");
}while(count<len);
printf("\nNo of page faults : %d\n",pf);
}
int check(int x)
{
int i;
for(i=0;i<r;i++)
if(cq[i]==x)
return(1);
return(0);
}
void addq(int x)
{
if(r==nof)
{ cq[f]=x;
f++;
}
else
{
cq[r]=x;
r++;
}
}

Input:
FIFO PAGE REPLACEMENT ALGORITHM
Enter the no of frames 3
Enter the number of elements 8
Enter the elements 1 2 3 3 4 526

Output:
CONTENTS OF FRAMES DURING PROCESSING
F[0] F[1] F[2] Page fault
1 -1 -1 *
1 2 -1 *
1 2 3 *
1 2 3 -
4 2 3 *
4 5 3 *
4 5 2 *
6 5 2 *

No of page faults: 7
EX.NO.12b) LRU PAGE REPLACEMENT ALGORITHM

Aim:
To write a Program to simulate LRU Page Replacement Algorithm
Algorithm:
Step1: Start the process
Step2: Declare the size
Step3: Get the number of pages to be inserted
Step4: Get the value
Step5: Declare counter and stack
Step6: Select the least recently used page by counter value
Step7: Stack them according the selection.
Step8: Display the values
Step9: Stop the process
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int g=0,a[5],b[20],p=0,q=0,m=0,h,k,i,q1=1,j,u;
char f='F';
clrscr();
printf("Enter no:");
for(i=0;i<12;i++)
scanf("%d",&b[i]);
for(i=0;i<12;i++)
{if(p==0)
{
if(q>=3)
q=0;
a[q]=b[i];
q++;
if(q1<3)
{ q1=q;
g=1;
} }
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q1==3)&&(g!=1))
{ printf("-->%c",f);
m++;
}
p=0;
g=0;
if(q1==3)
{
for(k=0;k<q-1;k++)
{
if(b[i+1]==a[k])
p=1;
}
for(j=0;j<q1;j++)
{
u=0;
k=i;
while(k>(i-2)&&(k>=0))
{
if(b[k]==a[j])
u++;
k--;
}
if(u==0)
q=j;
}
}
else
{
for(k=0;k<q;k++)
{
if(b[i+1]==a[k])
p=1;
} } }
printf("\nNo of faults:%d",m);
getch();
}
Input:
LRU PAGE REPLACEMENT ALGORITHM
Enter the size of frame: 3
Enter the no. of elements: 10
Enter the elements:
701203042
Output:
Contents of frames during processing
F[1] F[2] F[3] PF
-1 -1 -1
7 -1 -1 *
7 0 -1 *
7 0 1 *
2 0 1 *
2 0 1 -
2 0 3 *
2 0 3 -
4 0 3 *
4 0 2 *
4 3 2 *
No. of page faults = 8
EX.NO.12c) LFU PAGE REPLACEMENT ALGORITHM

Aim:
To write a Program to simulate LFU Page Replacement Algorithm
Algorithm:
Step1: Start Program
Step 2: Read Number Of Pages And Frames
Step 3: Read Each Page Value
Step 4: Search For Page In The Frames
Step 5: If Not Available Allocate Free Frame
Step 6: If No Frames Is Free Repalce The Page With The Page That Is Leastly Used
Step 7: Print Page Number Of Page Faults
Step 8: Stop process
Program:
#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],optcal[50],count=0;
int optvictim();
void main()
{ printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHN");
printf("\n. ............................... ");
printf("\nEnter the no.of frames");
scanf("%d",&nof);
printf("Enter the no.of reference string"); s
canf("%d",&nor);
printf("Enter the reference string");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM");
printf("\n. .............................. ");
printf("\nThe given string");
printf("\n. .................. \n");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=0;i<nof;i++)
{
frm[i]=-1;
optcal[i]=0;
}
for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
for(i=0;i<nor;i++)
{ flag=0;
printf("\n\tref no %d ->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}
if(flag==0)
{ count++;
if(count<=nof)
victim++;
else
victim=optvictim(i);
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
}
printf("\n Number of page faults: %d",pf);
getch();
}
int optvictim(int index)
{
int i,j,temp,notfound;
for(i=0;i<nof;i++)
{
notfound=1;
for(j=index;j<nor;j++)
if(frm[i]==ref[j])
{
notfound=0;
optcal[i]=j;
break;
}
if(notfound==1)
return i;
}
temp=optcal[0];
for(i=1;i<nof;i++)
if(temp<optcal[i])
temp=optcal[i];
for(i=0;i<nof;i++)
if(frm[temp]==frm[i])
return i;
return 0;
}
Input:
OPTIMAL PAGE REPLACEMENT ALGORITHM
Enter no.of Frames ...3
Enter no.of reference string 6
Enter reference string..
654231
Output:
OPTIMAL PAGE REPLACEMENT ALGORITHM
The given reference string:
…………………. 6 5 4 2 3 1
Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1
No.of page faults...6
EX.NO.13a) SINGLE LEVEL DIRECTORY

Aim:
To develop a c program to simulate the single level directory.
Algorithm:
Step 1: Declare necessary variables
Step 2: Read directory and file to create
Step 3: if choice=2, Perform deletion by getting file name as input.
Step 4: if choice =3, return file name foud,if file is in directory, otherwise return not found
Step 5: if choice =4, display the single level directory structure if exist, otherwise not found.
Step 6: Stop Execution
Program:
#include<stdio.h>
#include<string.h>
struct s
{
char dname[10],fname[10][10];
int fcnt;
}dir;
void main()
{
int i,ch;
char f[30];
clrscr();
dir.fcnt = 0;
printf("\nEnter name of directory --");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n1. Create File\t2. Delete File\t3. Search File \n
4. Display Files\t5.Exit\nEnter your choice --");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the name of the file --");
scanf("%s",dir.fname[dir.fcnt]);
dir.fcnt++;
break;
case 2:
printf("\nEnter the name of the file --");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is deleted ",f);
strcpy(dir.fname[i],dir.fname[dir.fcnt-1]);
break;
}
}
if(i==dir.fcnt)
printf("File %s not found",f);
else
dir.fcnt--;
break;
case 3:
printf("\nEnter the name of the file --");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is found ", f);
break;
}
}
if(i==dir.fcnt)
printf("File %s not found",f);
break;
case 4:
if(dir.fcnt==0)
printf("\nDirectory Empty");
else
{
printf("\nThe Files are --");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]);
}
break;
default:
exit(0);
}
}
getch();
}

Input and Output:


Enter name of directory --CSE
1. Create File
2. Delete File 3. Search File
4. Display Files
5. Exit
Enter your choice –1
Enter the name of the file --A

1. Create File
2. Delete File 3. Search File
4. Display Files
5. Exit
Enter your choice –1
Enter the name of the file –B

1. Create File
2. Delete File 3. Search File
4. Display Files
5. Exit
Enter your choice –1
Enter the name of the file –C

1. Create File
2. Delete File 3. Search File
4. Display Files
5.Exit
Enter your choice –4
The Files are –A B C

1. Create File
2. Delete File 3. Search File
4. Display Files
5. Exit
Enter your choice –3
Enter the name of the file –ABC

File ABC not found


EX.NO13b) TWO LEVEL DIRECTORY STRUCTURE

Aim:
To write a Program to simulate two level file organization technique
Algorithm:
Step 1: Declare necessary variables, organize file structure based on choice
Step 2: if choice=1, Read directory (more than one by choosing choice)
Step 3: if choice=2, Read directory and file to create on the specified directory
Step 4: if choice=3, Perform deletion by getting directory and file name as input.
Step 5: if choice=4, return file name foud, if file is in directory, otherwise return not found
Step 6: if choice=5, display the two level directory structure if exist, otherwise not found.
Step 7: Stop Execution
Program:
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\tEnter your choice --");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter name of directory --");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2:
printf("\nEnter name of the directory --");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file --");
scanf("%s",dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3:
printf("\nEnter name of the directory --");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file --");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4:
printf("\nEnter name of the directory --");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file --");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}
printf("File %s not found",f);
goto jmp1;
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;
default:exit(0);
}
}
getch();
}
Input and Output:
1. Create Directory 2. Create File 3. Delete File 4. Search File 5. Display 6. Exit
Enter your choice --1
Enter name of directory --DIR1
Directory Created

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

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

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

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

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

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

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --5

Directory Files
DIR1 A1 A2
DIR2 B1 B2 B3

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --4

Enter name of the directory --DIR2


Enter the name of the file --B2
File B2 is found

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --4

Enter name of the directory --DIR1


Enter the name of the file --A3
File A3 not found

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --3

Enter name of the directory --DIR2


Enter name of the file --B1
File B1 is deleted

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --5

Directory Files
DIR1 A1 A2
DIR2 B3 B2
EX.NO.14a) SEQUENTIAL FILE ALLOCATION METHOD

Aim:
To write C Program for implementing sequential file allocation method
Algorithm:
Step 1: Start the Program.
Step 2: Get the number of memory partition and their sizes.
Step 3: Get the number of processes and values of block size for each process.
Step 4: First fit algorithm searches the entire entire memory block until a hole which is big enough
is encountered. It allocates that memory block for the requesting process.
Step 5: Best-fit algorithm searches the memory blocks for the smallest hole which can be allocated
to requesting process and allocates if.
Step 6: Worst fit algorithm searches the memory blocks for the largest hole and allocates it to the
process.
Step 7: Analyses all the three memory management techniques and display the best algorithm
which utilizes the memory resources effectively and efficiently.
Step 8: Stop the Program.

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j,b[20],sb[20],t[20],x,c[20][20];
clrscr();
printf("Enter no.of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter no. of blocks occupied by file%d",i+1);
scanf("%d",&b[i]);
printf("Enter the starting block of file%d",i+1);
scanf("%d",&sb[i]);
t[i]=sb[i];
for(j=0;j<b[i];j++)
c[i][j]=sb[i]++;
}
printf("Filename\tStart block\tlength\n");
for(i=0;i<n;i++)
printf("%d\t %d \t%d\n",i+1,t[i],b[i]);
printf("Enter file name:");
scanf("%d",&x);
printf("File name is:%d",x);
printf("length is:%d",b[x-1]);
printf("blocks occupied:");
for(i=0;i<b[x-1];i++)
printf("%4d",c[x-1][i]);
getch();
}
Input:
Enter no.of files: 2
Enter no. of blocks occupied by file1 4
Enter the starting block of file1 2
Enter no. of blocks occupied by file2 10
Enter the starting block of file2 5
Filename Start block length
1 2 4
2 5 10
Enter file name: file1

Output:
File name is: 12803 length is: 0blocks occupied
EX.NO.14b) INDEXED FILE ALLOCATION METHOD

Aim:
To Write a C Program to implement Indexed File Allocation method.

Algorithm:
Step 1: Start. Let n be the size of the buffer
Step 2: Check if there are any producer
Step 3: If yes check whether the buffer is full
Step 4: If number the producer item is stored in the buffer
Step 5: If the buffer is full the producer has to wait
Step 6: Check there is any consumer. If yes check whether the buffer is empty
Step 7: If number the consumer consumes them from the buffer
Step 8: If the buffer is empty, the consumer has to wait.
Step 9: Repeat checking for the producer and consumer till required
Step 10: Terminate the process.

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

Input:

Enter no of files : 2
Enter file 1 : A
Enter no of blocks in file 1 : 4
Enter the blocks of the file 1 : 12 23 9 4
Enter file 2 : G
Enter no of blocks in file 2 : 5
Enter the blocks of the file 2 : 88 77 66 55 44
Enter the file to be searched : G

Output:
FILE NAME NO OF BLOCKS BLOCKS OCCUPIED
G 5 88 ->77->66->55->44.
EX.NO.14c) LINKED FILE ALLOCATION METHOD

Aim:
To Write a C Program to implement Linked File Allocation method.
Algorithm:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom of the stack
Step 6: Stop the allocation.

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

Input:
Enter no of files : 2
Enter file 1 : A
Enter no of blocks in file 1 : 4
Enter the blocks of the file 1 : 12 23 9 4
Enter file 2 : G
Enter no of blocks in file 2 : 5
Enter the blocks of the file 2 : 88 77 66 55 44
Enter the file to be searched: G

Output:
FILE NAME NO OF BLOCKS BLOCKS OCCUPIED
G 5 88, 77, 66, 55,

You might also like