System Programming Lab - Manual
System Programming Lab - Manual
SYSTEM PROGRAMMING
2. Write programs using the I/O system calls of UNIX operating system (open, read, write,
etc)
4. Given the list of processes, their CPU burst times and arrival times, display/print the
Gantt chart for FCFS and SJF. For each of the scheduling policies, compute and print the
average waiting time and average turnaround time. (2 sessions)
5. Given the list of processes, their CPU burst times and arrival times, display/print the
Gantt chart for Priority and Round robin. For each of the scheduling policies, compute
and print the average waiting time and average turnaround time. (2 sessions)
7. Implement the Producer – Consumer problem using semaphores (using UNIX system calls).
System Programming
Experiment List
Exp .No Contents CLOS
3 Shell Programming:
a. Discuss about the UNIX Shell Programming Commands. 1
4 Shell Programming:
5 Shell Programming
a. Practice To write a C program to find 3
i. Maximum of three numbers
ii. Fibonacci series
iii. Arithmetic operation using case
b. Recognize how we write a program in vi editor using
4
fedora
a. Explain how to create a file ,read from the file and write 1
in a file
b. Practice to write a C program for 3
i. Reading from a file
ii. Writing into a file
iii. File Creation
8 a. Discuss the ls and grep 1
command
b. Practice to write a C program for
i. Implementation of ls 3
command
ii. Implementation of grep
command
9 1
a. Explain how to implement the CPU scheduling algorithm
for FCFS.
b. Practice Given the list of processes, their CPU burst times and 3
arrival times,
12 1
a. Discuss what is Producer-Consumer Problem using
Semaphore
b. Practice To write a C program to implement the Producer & 3
consumer Problem (Semaphore)
compiler. Or
Code::Blocks isa free C++ compiler which meets the most demanding needs of its users. It is
designed to be very extensible and fully configurable.
It is a cross-platform IDE that supports compiling and running multiple programming languages. It
is available for download from:
http://www.codeblocks.org/
The best way to learn a programming language is to try writing programs and test them on a
computer. To do this, we need several pieces of software:
An editor with which to write and modify the C++ program components or source code,
A compiler with which to convert the source code into machine instructions which can be
executed by the computer directly,
A linking program with which to link the compiled program components with each other
and with a selection of routines from existing libraries of computer code, in order to form
the complete machine-executable object program,
A debugger to help diagnose problems, either in compiling programs in the first place,
or if the object program runs but gives unintended results.
There are several editors available for Linux (and Unix systems in general). Two of the most
popular editors are emacs and vi. For the compiler and linker, we will be using the GNU g++
compiler/linker, and for the debugger we will be using the GNU debugger gdb. For those that
prefer an integrated development environment (IDE) that combines an editor, a compiler, a
linking program and a debugger in a single programming environment (in a similar way to
Microsoft Developer Studio under Windows NT), there are also IDEs available for Linux (e.g. V
IDE, kdevelop etc.)
GCC stands for ―GNU Compiler Collection‖. GCC is an integrated distribution of compilers for
several major programming languages. These languages currently include C, C++, Objective-C,
Objective-C++, Java, Fortran , and Ada.
The abbreviation GCC has multiple meanings in common use. The current official meaning is
―GNU Compiler Collection‖, which refers generically to the complete suite of tools. The name
historically stood for ―GNU C Compiler‖, and this usage is still common when the emphasis is on
compiling C programs. Finally, the name is also used when speaking of the language-
independent component of GCC: code shared among the compilers for all supported languages.
The language-independent component of GCC includes the majority of the optimizers, as well as
the ―back ends‖ that generate machine code for various processors.
The part of a compiler that is specific to a particular language is called the ―front end‖.
In addition to the front ends that are integrated components of GCC, there are several other front
ends that are maintained separately. These support languages such as Pascal, Mercury, and
COBOL. To use these, they must be built together with GCC proper.
Most of the compilers for languages other than C have their own names. The C++ compiler is
G++, the Ada compiler is GNAT, and so on. When we talk about compiling one of those
languages, we might refer to that compiler by its own name, or as GCC. Either is correct.
Historically, compilers for many languages, including C++ and Fortran, have been implemented
as ―preprocessors‖ which emit another high level language such as C. None of the
compilers included in GCC are implemented this way; they all generate machine code directly.
This sort of preprocessor should not be confused with the C preprocessor, which is an integral
feature of the C, C++, Objective-C and Objective-C++ languages.
GCC Command Options
When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The
―overall options‖ allow you to stop this process at an intermediate stage. For example, the
-c option says not to run the linker. Then the output consists of object files output by the
assembler.
Other options are passed on to one stage of processing. Some options control the preprocessor
and others the compiler itself. Yet other options control the assembler and linker; most of these
are not documented here, since you rarely need to use any of them.
Most of the command line options that you can use with GCC are useful for C programs; when
an option is only useful with another language (usually C++), the explanation says so explicitly.
If the description for a particular option does not mention a source language, you can use that
option with all supported languages.
The gcc program accepts options and file names as operands. Many options have multi-letter
names; therefore multiple single-letter options may not be grouped: -dr is very different from `-
d -r'.
You can mix options and other arguments. For the most part, the order you use doesn't matter.
Order does matter when you use several options of the same kind; for example, if you specify -L
more than once, the directories are searched in the order specified.
Many options have long names starting with `-f' or with `-W'—for example, -fmove-loop-
invariants, -Wformat and so on. Most of these have both positive and negative forms; the
negative form of -ffoo would be -fno-foo. This manual documents only one of these two forms,
whichever one is not the default.
However, the use of gcc does not add the C++ library. g++ is a program that calls GCC and
treats `.c', `.h' and `.i' files as C++ source files instead of C source files unless -x is used, and
automatically specifies linking against the C++ library. This program is also useful when
precompiling a C header file with a `.h' extension for use in C++ compilations. On many
systems, g++ is also installed with the name c++.
When you compile C++ programs, you may specify many of the same command-line options
that you use for compiling programs in any language; or command-line options meaningful for C
and related languages; or options that are meaningful only for C++ programs.
The Vi Editor
All Linux configuration files are written in plain English, easy to read and to adapt. You use a
text-editor to write or make changes to such files. The two most popular, powerful, and
unfortunately "difficult" text editors, both of which are found in every Linux are Vi and Emacs.
Most GUI-based editors, such as Kedit, are easier to manage. But don't make the mistake of
thinking that a GUI-based editor is all you need. There are situations that crop up with Linux that
require a text-mode editor -- in other words, when you don't have the luxury of accessing a GUI
desktop at all. Vi and Emacs are the only tools that come with every Linux that work in text
mode, so learning one or the other is mandatory.
Getting Started
To start Vi, open a terminal or console and simply type "vi" (without the quotation marks)
followed by the name of any existing file or a new file you want to create.
Vi works in two main modes, one for editing text and the other for giving commands. To switch
between the two modes you use the I (Insert) and Esc keys. The program opens in the
Command mode, which is used for cursor movements, delete, cut, copy, paste, and saving
changes.
The Insert mode is what you'll work in most of the time. You use it to make changes in an open
file. Enter the Insert mode by pressing the I key. Newer Vi versions will display the word
"INSERT' on the bottom line while you're in Insert mode.
Press the Esc key to switch Vi back to Command mode. As soon as you hit the Esc key the text
"INSERT" on the bottom line disappears.
You save your changes to the open file from the Command mode. Press Shift-ZZ to save.
If you make a mistake when saving a file, such as pressing Ctrl-ZZ or closing Vi before saving
the file, you'll end up with a swap file (akin to a DOS/Windows temp file) in addition to the
original file. Usually the swap file will have the .swp extension. The original file will not contain
the recent changes you made; attempting to reopen it will result in an error message.
The swap file is not readable but can be recovered by typing a command like this at the $ prompt
and pressing Enter:
Common Vi Commands
Press Key(s):* Function:
I Insert text before the cursor
A Insert text after the cursor
: Switch to ex mode
$ Go to last place on the line
^ Go to first place on the line
W Next word
B Previous word
Shift-G Last line of the file
20 Shift-G Go to line 20
Y Copy. (Note: Y3W = copy 3 words; Y3J = copy 4 lines.)
P Paste
D Cut
X Delete character under the cursor
Steps for Creation of Program on Linux
1. Make a new file called "test" by opening a console and typing this line after the $ prompt
and press Enter:
vi test
2. You'll get an empty console screen since Vi will start with the empty new file. Remember, Vi
always starts Command mode, so press the I (Insert) key to enter the Insert mode. If you're ever
not sure whether you're in Insert mode, you can always just hit I again.
5. Save the file by pressing the ―:wq‖ key. This command save the file as well as exit from the
file. But if you just want to save without exiting then press ―:w‖.
6. Vi should close and you should see your $ prompt back in the console.
7. The program can be compiled by writing the following command on the $ prompt:
8. If there are any errors in the program it will be displayed on the prompt with line numbers.
9. To remove the errors reopen the file you created. At the $ prompt, type this and press Enter:
vi test
This time Vi opens up to the text in your file, not a blank screen.
10. Now save the file again by pressing Esc to enter the Command mode and recompile it.
11. If noerrors then now run the program to get the output by typing this on $ prompt
and press enter:
./a.out
12. Wheneveryou make any changes in your program, you need to save and recompile
it before running it for the output.
Page 16
LAB 02 CLO (1,3, 4)
UNIX COMMANDS
Date:
AIM :
To Discuss and execute the commands in UNIX.
COMMAND :
1. Date Command :
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‟ format
h = Abbrevated month day.
H = Display the hour.
L = Day of the year.
m = Month of the year.
M = Minute.
P = Display AM or PM
S = Seconds
T = HH:MM:SS format
u = 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 Command :
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>
Page 17
Here the first syntax gives the entire calendar for given year & the second Syntax gives
the calendar of reserved month of that year.
3. Echo Command :
This command is used to print the arguments on the screen .
Syntax : $echo <text>
Multi line echo command :
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 Command :
It is used to display the arguments in „#‟ symbol .
Syntax : $banner <arguments>
5.’who’ Command :
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’ Command :
Display the details of the current working directory.
Syntax : $who am i
7.’tty’ Command :
It will display the terminal name.
Syntax : $tty
Page 18
9.’CLEAR’ Command :
It is used to clear the screen.
Syntax : $clear
10.’MAN’ Command :
It help us to know about the particular command and its options & working. It is like
„help‟ command in windows .
Syntax : $man <command name>
2. MKDIR Command :
To create or make a new directory in a current directory .
Syntax : $mkdir <directory name>
3. CD Command :
To change or move the directory to the mentioned directory .
Syntax : $cd <directory name.
4. RMDIR Command :
To remove a directory in the current directory & not the current directory itself.
Syntax : $rmdir <directory name>
Page 19
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 if the 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 Command :
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 Command :
To permanently remove the file we use this command .
Syntax :
$rm <filename>
Page 20
8. WORD Command :
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>
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
continue scrolling.
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>
Page 21
PIPE : It is a mechanism by which the output of one command can be channeled into the input
of 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]”
2. Command: WRITE
Description: This command is used to communicate with other users, who are logged in at
the same time.
Syntax: $write <user name>
3. Command: WALL
Description: This command sends message to all users those who are logged in using the
unix server.
Syntax: $wall <message>
4. Command: MAIL
Description: It refers to textual information, that can be transferred from one user to
another
Syntax: $mail <user name>
5. Command: REPLY
Description: It is used to send reply to specified user.
Syntax: $reply<user name>
RESULT:
Page 22
vi EDITOR COMMANDS
DATE :
AIM :
To discuss 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 modes available 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 each line. 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 to another press escape key.
1. ESC a Command :
This command is used to move the edit mode and start to append after the current
character.
Syntax : <ESC> a
2. ESC A COMMAND :
This command is also used to append the file , but this command append at the end of
current line.
Page 23
Syntax : <ESC> A
Page 24
3. ESC i Command :
This command is used to insert the text before the current cursor position.
Syntax : <ESC> i
4. ESC I Command :
This command is used to insert at the beginning of the current line.
Syntax : <ESC> I
5. ESC o Command :
This command is insert a blank line below the current line & allow insertion of
contents.
Syntax : <ESC> o
6. ESC O Command :
This command is used to insert a blank line above & allow insertion of contents.
Syntax : <ESC> O
7. ESC r Command :
This command is to replace the particular character with the given characters.
Syntax : <ESC> rx Where x is the new character.
8. ESC R Command :
This command is used to replace the particular text with a given text.
Syntax : <ESC> R text
9.<ESC> s Command :
This command replaces a single character with a group of character .
Syntax : <ESC> s
10.<ESC> S Command :
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 . It can 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 used to move the cursor for a number of character.
Syntax : <ESC> l – single character to right.
<ESC> nl - „n‟ characters to right.
Page 25
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.
6.<ESC> + Command :
This command is used to move to the beginning of the next line.
Syntax :
<ESC> + <ESC> n+
7.<ESC> - Command :
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 Command :
This command is used to move back to the previous word (or) a number of words.
Syntax :
<ESC> b <ESC>nb
Page 26
12.<ESC> e Command :
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 Command :
To delete a character to right of current cursor positions , this command is used.
Syntax :
<ESC> x <ESC> nx
2.<ESC> X Command :
To delete a character to left of current cursor positions , this command is used.
Syntax :
<ESC> X <ESC> nX
3.<ESC> dw Command :
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 Command :
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$ Command :
This command is used to delete the text from current cursor position to last character of
current line.
Syntax : <ESC> d$
Page 27
2.<ESC> q! Command :
To quit the given text without saving.
Syntax : <ESC> :q!
3.<ESC> wq Command :
This command quits the vi editor after saving the text in the mentioned file.
Syntax : <ESC> :wq
4.<ESC> x Command :
This command is same as „wq‟ command it saves and quit.
Syntax : <ESC> :x
5.<ESC> q Command :
This command would quit the window but it would ask for again to save the file.
Syntax : <ESC> : q
RESULT:
Page 28
LAB 03 CLO (3,4)
AIM :
To discuss and Practice the UNIX Shell Programming Commands.
INTRODUCTION :
Shell programming is a group of commands grouped together under single filename.
After logging onto 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
programmable features
Bourne Shell - bsh or sh - also restricted shell - bsh : Sophisticated pattern matching
and file name substitution
Korn Shell : Backwards compatible with Bourne Shell Regular expression
substitution emacs editing mode
Thomas C-Shell - tcsh : Based on C-Shell Additional ability to use emacs to edit the
command line Word completion & spelling correction Identifying your
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 [ ] are used for filename expansion. The <, >,
Page 29
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?"
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 any process spawned from that shell. They go out of scope when
the script ends.
EXAMPLE
VARIABLE_NAME=value
export VARIABLE_NAME
Page 30
PATH=/bin:/usr/bin:.
export PATH
Page 31
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.
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
Page 32
-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 their values 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
Reading user input The read command takes a line of input from the user and assigns it to
a variable(s) on the 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
square brackets. 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 next action , if not it goes to the else part.
Page 33
2. if…else
Syntax :
If cp $ source $ target
Then
Echo File copied successfully
Else
Echo Failed to copy the file.
3. ested if
if condition
then
command
if condition
then
command
else
command
fi
fi
EXAMPLE
The if construct is: The case command construct is:
if command case variable_name in
then pattern1)
block of statements statements
fi ;;
-------------------------------------- pattern2)
if [ expression ] statements
then ;;
block of statements pattern3)
fi ;;
-------------------------------------- *) default value
The if/else/else if construct is: ;;
if command esac
then case "$color" in
block of statements blue)
elif command echo $color is blue
then ;;
block of statements green)
elif command echo $color is green
then ;;
Page 34
block of statements red|orange)
else echo $color is red or orange
block of statements ;;
fi *) echo "Not a color" # default
------------------------------ esac
if [ expression ] The if/else construct is:
then if [ expression ]
block of statements then
elif [ expression ] block of statements
then else
block of statements block of statements
elif [ expression ] fi
then --------------------------------------
block of statements
else
block of statements
fi
--------------------------------------
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 the next 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 do
block of statements block of statements
done done
------------
until [ expression ]
Page 35
do
block of statements
done
------------
until control command
do
commands
done
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 word3
set 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
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
Page 36
–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
RESULT:
Page 37
LAB 04 CLO (1,3,4)
SHELL PROGRAMMING
Aim:
To Practice a shell program to concatenate two strings.
Algorithm:
Step1: Enter into the vi editor and go to the insert mode for entering the code
Step2: Read the first string.
Step3: Read the second string
Step4: Concatenate the two strings
Step5: Enter into the escape mode for the execution of the result and verify the output
Program:
echo “enter the first string”
read str1
echo “enter the second string”
read str2
echo “the concatenated string is” $str1$str2
Sample I/P:
Sample O/P:
Result:
Thus the shell program to concatenate two strings is executed and output is verified
successfully.
Page 38
COMPARISON OF TWO STRINGS
Date:
Aim:
To Practice a shell program to compare the two strings.
Algorithm:
Step1: Enter into the vi editor and go to the insert mode for entering the code
Step2: Read the first string.
Step3: Read the second string
Step4: Compare the two strings using the if loop
Step5: If the condition satisfies then print that two strings are equal else print two
strings are not equal.
Step6: Enter into the escape mode for the execution of the result and verify the output
Program:
echo “enter the first string”
read str1
echo “enter the second string”
read str2
if [ $str1 = $str2 ]
then
echo “strings are equal”
else
echo “strings are unequal”
fi
Sample I/P:1
Enter first string: hai
Enter second string: hai
Sample O/P:1
The two strings are equal
Sample I/P:2
Enter first string: hai
Enter second string: cse
Sample O/P:2
The two strings are not equal
Result:
Thus the shell program to compare the two strings is executed and output is verified
successfully.
Page 39
Lab 05 CLO (3,4)
Aim:
Practice a shell program to find greatest of three numbers.
Algorithm:
Program:
echo "enter A"
read a
echo "enter B"
read b
echo "enter C"
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "A is greater"
elif [ $b -gt $a -a $b -gt $c ]
then
echo "B is greater"
else
echo "C is greater"
fi
Sample I/P:
Enter A:23
Enter B:45
Enter C:67
Sample O/P:
C is greater
Result:
Thus the shell program to find the maximum of three numbers is executed and output is
verified successfully.
Page 40
FIBONACCI SERIES
Date:
Aim:
Algorithm :
Program :
echo enter the number
read n
a=-1
b=1
i=0
while [ $i –le $n ]
do
t=`expr $a + $b`
echo $t
a=$b
b=$t
i=`expr $i + 1
done
Sample I/P :
Enter the no: 5
Sample O/P:
0
1
1
2
3
5
Result :
Thus the shell program to find the fibonacci series is executed and output is
Page 41
ARITHMETIC OPERATIONS USING CASE
Date:
Aim:
Algorithm :
Page 42
Sample I/P :
1. Addition
2. 2.Subraction
Operating
System Lab
Manual CS
2254
Division
Enter your choice:1
Enter the value of b:3
Enter the value of c:4
b is 3 c is 4
the sum is 7
Sample O/P:
b is 3 c is 4
the sum is 7
Result :
Thus the shell program to perform arithmetic operations using case is executed and
output is verified successfully.
Page 43
Lab 06 CLO (1,3,4)
SYSTEM CALLS
AIM:
To Practice a C program for create a process in UNIX.
ALGORITHM:
PROGRAM:
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”)
}
}
Page 44
SAMPLE OUTPUT:
$cc pc.c
$a.out
parent process$ child process
$ps
PID CLS PRI TTY TIME COMD
5913 TS 70 pts022 0:00 ksh
6229 TS 59 pts022 0:00 ps
Page 45
Ex.No:3b EXECUTING A COMMAND
Date:
AIM:
To Practice 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
SAMPLE OUTPUT:
$ sh exec.sh
program for executing UNIX command using shell programming
Welcome
PID CLS PRI TTY TIME COMD
958 TS 70 pts001 0:00 ksh
971 TS 70 pts001 0:00 sh
972 TS 59 pts001 0:00 ps
3 41 81 e
RESULT:
Thus the program was executed and verified successfully.
Page 46
SLEEP COMMAND
Date:
AIM:
Practice a C Program
To create child with sleep command.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create process using fork and assign into a variable.
STEP 3: If the value of variable is < zero print not create and > 0 process create and
else print child create.
STEP 4: Create child with sleep of 2.
STEP 5: Stop the program.
PROGRAM:
void main()
{
int id=fork();
if(id==-1)
{
printf(“cannot create the file”);
exit(1);
}
else if(id==0)
{
}
}
else
{
}
Page 47
sleep(2);
printf(“this is
child process”); printf(“parent process”);
exit(1);
Page 48
OUTPUT:
$ cc sleep.c
$ a.out
parent process$ this is child process
RESULT:
Thus the program was executed and verified successfully.
Page 49
SLEEP COMMAND USING GETPID
Date:
AIM:
Practice a C Program
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(“\nParent process”);
Page 50
sleep(10);
printf(“\n Child Process id is %d ”,getpid());
printf(“\n Its parent process id is %d”,getppid());
printf(“\nParent terminates\n”);
}
}
OUTPUT:
$ cc sleepid.c
$ a.out
parent process
child process
child process id is 12691
its parent process id is 12690
child process after sleep=5
child process id is 12691
its parent process id is 12690
child process after sleep=10
child id is 12690
parent id is 11383
parent terminates
$
RESULT:
Thus the program was executed and verified successfully.
Page 51
SIGNAL HANDLING
Date:
AIM:
Practice a C Program
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 operations
ps
echo enter the pid
read pid
kill-9 $pid
echo finished
OUTPUT:
$sh kill.sh
program for performing KILL operations
PID CLS PRI TTY TIME COMD
858 TS 70 pts001 0:00 ksh
858 TS 70 pts001 0:00 sh
858 TS 59 pts001 0:00 ps
enter the pid
872
killed
$sh kill.sh
program for performing KILL operations
PID CLS PRI TTY TIME COMD
858 TS 70 pts001 0:00 ksh
Page 52
858 TS 70 pts001 0:00 sh
858 TS 59 pts001 0:00 ps
enter the pid
876
UX:kill(kill.sh):ERROR: no such proccess
$sh kill.sh
program for performing KILL operations
PID CLS PRI TTY TIME COMD
858 TS 70 pts001 0:00 ksh
858 TS 70 pts001 0:00 sh
858 TS 59 pts001 0:00 ps
enter the pid
858
finished
RESULT:
Thus the program was executed and verified successfully.
Page 53
WAIT COMMAND
Date:
AIM:
Practice a 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:
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:
Page 54
$cc wait.c
$a.out
initial value of i 10
value of i 20
child teriminated
value of i in parent process 10$
RESULT:
Thus the program was executed and verified successfully.
Page 55
LAB 07 CLO (1,3,4)
AIM:
Practice a C Program
ALGORITHM:
PROGRAM:
#include<stdio.h>
int main()
{
char str[100];
FILE *fp;
fp=fopen("file1.dat","r");
while(!feof(fp))
{
fscanf(fp,"%s",str);
printf(" %s ",str);
}
fclose(fp);
}
OUTPUT:
$ vi read1.c
$gcc read1.c
$ ./a.out
hai this is a program to read the content of the file.
RESULT:
Page 56
WRITING INTO A FILE
Date
AIM:
Practice a C Program
ALGORITHM:
PROGRAM:
#include<stdio.h>
int main()
{
char str[100];
FILE *fp;
printf("Enter the string");
gets(str);
fp=fopen("file1.dat","w+");
while(!feof(fp))
{
fscanf(fp,"%s",str);
}
fprintf(fp,"%s",str);
}
OUTPUT:
$ gcc write.c
$ ./a.out
Enter the string: os lab
$vi file1.dat
os lab
RESULT:
Thus C program to write data into a file was executed successfully.
Page 57
FILE CREATION
Date:
AIM:
Practice a C Program
To create a file.
ALGORITHM:
PROGRAM:
void main()
{
int id;
if(id=creat(“z.txt”,0)==-1)
{
printf(“cannot create the file”);
exit(1);
}
else
{
printf(“file is created”);
exit(1);
}
OUTPUT:
$ cc fc.c
$ a.out
file is created $
RESULT:
Thus the C program to create a file was executed successfully.
Page 58
Lab 08 CLO (3,4)
IMPLEMENTATION OF ls COMMAND
Date:
Date:
AIM:
Practice 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.
2. Check if the second argument (i.e. directory to be listed) is valid or not. If not then
exit.
3. Print the content of the directory till it becomes NULL.
4. 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:
[root@lab1cab01 orbit]# gcc lsdemo.c
[root@lab1cab01 orbit]# ./a.out
Page 59
You have provided only 1 argument
[root@lab1cab01 orbit]# ./a.out /xyz/foo
RESULT:
Thus the program for implementing the ls command was executed and the output was
verified successfully.
Page 60
Lab 09 CLO (1,3,4)
AIM:
Practice a C Program
to implement the CPU scheduling algorithm for FIRST
COME FIRST SERVE.
PROBLEM DESCRIPTION:
Cpu scheduler will decide which process should be given the CPU for its execution.For this
it use different algorithm to choose among the process. one among that algorithm is fcfs
algorithm.
In this algorithm the process which arrive first is given the cpu after finishing its request
only it will allow cpu to execute other process.
ALGORITHM:
PROGRAM
#include<stdio.h>
Page 61
struct process
{
int id,wait,ser,tottime;
}p[20];
main()
{
int i,n,j,totalwait=0,totalser=0,avturn,avwait;
printf("enter number of process");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter process_id");
scanf("%d",&p[i].id);
printf("enter process service time");
scanf("%d",&p[i].ser);
}
p[1].wait=0;
p[1].tottime=p[1].ser;
for(i=2;i<=n;i++)
{
for(j=1;j<i;j++)
{
p[i].wait=p[i].wait+p[j].ser;
}
totalwait=totalwait+p[i].wait;
p[i].tottime=p[i].wait+p[i].ser;
totalser=totalser+p[i].tottime;
}
avturn=totalser/n;
avwait=totalwait/n; printf("Id\
tservice\twait\ttotal");
for(i=1;i<=n;i++)
{
printf("\n%d\t%d\t%d\t%d\n",p[i].id,p[i].ser,p[i].wait,p[i].tottime);
}
printf("average waiting time %d\n",avwait);
printf("average turnaround time %d\n",avturn);
}
OUTPUT
Page 62
enter process_id902
enter process service time3
enter process_id903
enter process service time5
enter process_id904
enter process service time2
Id service wait total
901 4 0 4
902 3 4 7
903 5 7 12
904 2 12 14
average waiting time 5
average turnaround time 8
RESULT:
Thus the C program to implement CPU scheduling algorithm for first come first
serve was executed successfully.
Page 63
SHORTEST JOB FIRST
Date :
AIM:
Practice a C Program
to implement the CPU scheduling algorithm for Shortest job
first.
PROBLEM DESCRIPTION:
Cpu scheduler will decide which process should be given the CPU for its execution.
For this it use different algorithm to choose among the process. one among that algorithm is sjf
algorithm.
In this algorithm the process which has less service time given the cpu after finishing its
request only it will allow cpu to execute next other process.
ALGORITHM:
Step1:Get the number of process.
Step2:Get the id and service time for each process.
Step3:Initially the waiting time of first short process as 0 and total time of first
short is process the service time of that process.
Step4:Calculate the total time and waiting time of remaining process.
Step5:Waiting time of one process is the total time of the previous process.
Step6:Total time of process is calculated by adding the waiting time and service
time of each process.
Step7:Total waiting time calculated by adding the waiting time of each process.
Step8:Total turn around time calculated by adding all total time of each process.
Step9:calculate average waiting time by dividing the total waiting time by total
number of process.
Step10:Calculate average turn around time by dividing the total waiting time by
total number of process.
Step11:Display the result.
PROGRAM:
#include<stdio.h>
struct ff
{
int pid,ser,wait;
}p[20];
struct ff tmp;
Page 64
main()
{
int i,n,j,tot=0,avwait,totwait=0,tturn=0,aturn;
printf("enter the number of process");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter process id");
scanf("%d",&p[i]);
printf("enter service time");
scanf("%d",&p[i].ser);
p[i].wait=0;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i].ser>p[j].ser)
{
tmp=p[i];
p[i]=p[j];
p[j]=tmp;
}
}
}
printf("PID\tSER\tWAIT\tTOT\n");
for(i=0;i<n;i++)
{
tot=tot+p[i].ser;
tturn=tturn+tot;
p[i+1].wait=tot;
totwait=totwait+p[i].wait;
printf("%d\t%d\t%d\t%d\n",p[i].pid,p[i].ser,p[i].wait,tot);
}
avwait=totwait/n;
aturn=tturn/n;
printf("TOTAL WAITING TIME :%d\n",totwait);
printf("AVERAGE WAITING TIME : %d\n",avwait);
printf("TOTAL TURNAROUND TIME :%d\n",tturn);
printf("AVERAGE TURNAROUND TIME:%d\n",aturn);
}
OUTPUT :
[root@lab1cab5 home]# ./a.out
enter the number of process4
Manual CS 2254
Page 66
Lab 10 CLO (1,3)
ROUND ROBIN
Date:
AIM :
Practice a C Program
to simulate the CPU scheduling algorithm for round robin
PROBLEM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its execution .For
this it use different algorithm to choose among the process .one among that algorithm is Round
robin algorithm.
In this algorithm we are assigning some time slice .The process is allocated according to
the time slice ,if the process service time is less than the time slice then process itself will
release the CPU voluntarily .The scheduler will then proceed to the next process in the ready
queue .If the CPU burst of the currently running process is longer than time quantum ,the timer
will go off and will cause an interrupt to the operating system .A context switch will be
executed and the process will be put at the tail of the ready queue.
ALGORITHM:
PROGRAM
/*
This program has assumed that the inputs are given in ordered fashion according to their
arrival times.
*/
struct roundRobin
Page 67
{
int pburst,pburst1,wtime,endtime,arrivt,boolean,flagcntl;
char pname[5];
}a[5];
int n,tq;
void input();
void initialize();
void calculate();
void display_waittime();
int main()
{
input();
initialize();
calculate();
display_waittime();
//getch();
//return 0;
}
void input()
{ int i;
printf("Enter Total no. of processes\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process name:");
scanf("%s",&a[i].pname);
printf("Enter process burst time:");
scanf("%d",&a[i].pburst);
printf("Enter process arrival time:");
scanf("%d",&a[i].arrivt);
}
printf("\nEnter the time quantum/Time Slice:");
scanf("%d",&tq);
}
void initialize()
{ int i;
for(i=0;i<n;i++)
{
a[i].pburst1=a[i].pburst;
a[i].wtime=0;
a[i].endtime=0;
a[i].boolean=0;
a[i].flagcntl=0;
}
Page 68
}
void calculate()
{ int i,j=0,k=0,flag=1,count=0;
printf("\n---GANTT CHART---\n");
printf("0 | ");
while(flag)
{
for(i=0;i<n;i++)
{
if((k<n)&&(a[i].arrivt<=count)&&(a[i].flagcntl==0)) //calculating waiting time for first
time
{
a[i].wtime=count-a[i].arrivt;
a[i].endtime=count;
a[i].boolean=1;
a[i].flagcntl=1;
k++;
}
if((a[i].pburst1>tq)&&(a[i].arrivt<=count))
{
if(a[i].boolean==1)
a[i].boolean=0;
else
a[i].wtime=a[i].wtime+(count-a[i].endtime);
count=count+tq;
a[i].pburst1=a[i].pburst1-tq;
a[i].endtime=count;
printf("%d %s| ",count,a[i].pname);
}
else if((a[i].pburst1>0) && (a[i].pburst1<=tq) && (a[i].arrivt<=count))
{
if(a[i].boolean==1)
a[i].boolean=0;
else
a[i].wtime=a[i].wtime+(count-a[i].endtime);
count=count+a[i].pburst1;
a[i].endtime=count;
printf("%d %s| ",count,a[i].pname);
a[i].pburst1=0;
j++;
}
else if(j==n) flag=0;
}//end of for loop
void display_waittime()
{ int i,tot=0,turn=0;
Page 69
for(i=0;i<n;i++)
{
printf("\n\nWaiting time for Process %s is %d",a[i].pname,a[i].wtime);
tot=tot+a[i].wtime;
turn=turn+a[i].endtime-a[i].arrivt;
}
printf("\n\n\tAverage waiting time=%f",(float)tot/(float)n);
printf("\n\tAverage turnaround time=%f\n",(float)turn/(float)n);
}
OUTPUT:
[root@lab1cab7 orbit]# gcc roundrobin.c
[root@lab1cab7 orbit]# ./a.out
Enter Total no. of processes
3
Enter process name:A
Enter process burst time:4
Enter process arrival time:0
Enter process name:B
Enter process burst time:3
Enter process arrival time:3
Enter process name:C
Enter process burst time:2
Enter process arrival time:3
---GANTT CHART---
0 | 2 A| 4 A| 6 B| 8 C| 9 B|
RESULT:
Thus the C program to simulate CPU scheduling algorithm for round robin was
executed successfully.
Page 70
PRIORITY SCHEDULING
Date:
AIM:
Practice a C Program
to implement CPU scheduling algorithm for priority scheduling.
PROBLEM DESCRIPTION:
Cpu scheduler will decide which process should be given the CPU for its execution.For this
it use different algorithm to choose among the process. one among that algorithm is fcfs
algorithm.
In this algorithm the process which arrive first is given the cpu after finishing its request
only it will allow cpu to execute other process.
ALGORITHM:
Step1:Get the number of process,burst time and priority.
Step2:Using for loopi=0 to n-1 do step 1 to 6.
Step3:If i=0,wait time=0,T[0]=b[0];
Step4:T[i]=T[i-1]+b[i] and wt[i]=T[i]-b[i].
Step5: Total waiting time is calculated by adding the waiting time for lack process.
Step6: Total turn around time is calculated by adding all total time of each process.
Step7: Calculate Average waiting time by dividing the total waiting time by total numberof
process.
Step8: Calculate Average turn around time by dividing the total time by the number of
process.
Step9: Display the result.
PROGRAM:
void main()
{
int i,j,n,t,turn[20],burst[20],p[20],wt[20],c[20];
float await,aturn,twait=0,tturn=0; printf(“\
nEnter the value of n:”); scanf(“%d”,&n);
printf(“\n Enter the process no burst and arrivaltime”);
for(i=0;i<n;i++)
{
scanf(“%d”,&c[i]);
scanf(“%d”,&burst[i]);
Page 71
scanf(“%d”,&p[i]);
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(p[i]>p[j])
{
t=p[i];
p[i]=p[j];
p[j]=t;
t=burst[i];
burst[i]=burst[j];
burst[j]=t;
t=c[i];
c[i]=c[j];
c[j]=t;
}
}
for(i=0;i<n;i++)
{
if(i==0)
{
wt[i]=0;
turn[i]=burst[i];
}
}
else
{
turn[i]=turn[i-1]+burst[i];
wt[i]=turn[i]-burst[i];
twait=twait+wt[i];
tturn=tturn+turn[i];
Page 72
}
await=twait/n;
aturn=tturn/n;
printf(“pno\tbtime\tatime\twtime\tttime”);
for(i=0;i<n;i++)
{
printf(“\n%d\t%d\t%d\t%d\t%d\n”,c[i],burst[i],p[i],wt[i],turn[i]);
}
printf(“\n The average waiting time is:%f”,await);
printf(“\n The average turn around time is:%f”,aturn);
OUTPUT:
$$ cc ps.c
$a.out
RESULT:
Thus C program to implement CPU scheduling algorithm for priority scheduling
was executed successfully.
Page 73
Lab 11 CLO (1,3,4)
PRODUCER CONSUMER PROBLEM USING SEMAPHORE
Date :
AIM:
Practice a C Program
to implement the Producer & consumer Problem (Semaphore)
ALGORITHM:
PROGRAM :
#define BUFFERSIZE 10
int mutex,n,empty,full=0,item,item1;
int buffer[20];
int in=0,out=0,mutex=1;
void wait(int s)
{
while(s<0)
{
printf(“\nCannot add an item\n”);
exit(0)
}
s--;
}
Page 74
void signal(int s)
{
s++;
}
void producer()
{
do
{
wait (empty);
wait(mutex); printf(“\
nEnter an item:”);
scanf(“%d”,&item);
buffer[in]=item;
in=in+1;
signal(mutex);
signal(full);
}
while(in<n);
}
void consumer()
{
do
{
wait(full);
wait(mutex);
item1=buffer[out];
printf(“\nConsumed item =%d”,item1);
out=out+1;
signal(mutex);
signal(empty);
}
while(out<n);
}
void main()
{
printf(“Enter the value of n:”);
scanf(“%d “,&n);
empty=n;
while(in<n)
producer();
while(in!=out)
consumer();
}
OUTPUT:
$ cc prco.c
$ a.out
Enter the value of n :3
Enter the item:2
Enter the item:5
Enter the item:9
consumed item=2
consumed item=5
consumed item=9
Page 75
Lab 12 CLO (1,2,4)
AIM:
Practice a C Program
to implement memory management using paging technique.
ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, page size, number of pages and memory unit.
Step3 : If the memory limit is less than the base address display the memory
limit is less than limit.
Step4 : Create the page table with the number of pages and page address.
Step5 : Read the page number and displacement value.
Step6 : If the page number and displacement value is valid, add the displacement
value with the address corresponding to the page number and display the
result.
Step7 : Display the page is not found or displacement should be less than page
size.
Step8 : Stop the program.
PROGRAM:
#include<stdio.h>
#include<unistd.h>
void main()
{
int b[20],n,i,pa,p,a,d; printf(“\
nProgram for paging”);
scanf(“%d”,&n);
printf(“\nEnter the base address:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&b[i]);
}
printf(“\nEnter the logical address:”);
scanf(“%d”,&p);
for(i=0;i<n;i++)
{
if(i==p)
{
pa=b[i]+d;
a=b[i];
printf(“\n\tPageNo.\t BaseAdd. PhysicalAdd. \n\t %d \t %d \t %d \t
Page 76
”,p,a,pa);
}
}
printf(“\nInvalid page”);
}
Sample Input 1:
Program for paging
Enter the number of pages:2
Enter the base address:
100
150
Enter the Logical address:50
Enter the page number:1
Sample Output 1:
PageNo. BaseAdd. PhysicalAdd.
1 150 200
Sample Input 2:
Program for paging
Enter the number of pages:1
Enter the base address:
100
Enter the Logical address:2
Enter the page number:2
Sample Output 2:
Invalid page.
RESULT:
Thus the program for implementing the paging concept was executed and the output
was verified successfully.
Page 77
Lab 13 CLO (1,2,4)
AIM:
Practice a C Program
to implement memory management using segmentation
ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, number of segments, size of each segment, memory
limit.
Step3 : If memory address is less than the base address display “invalid memory
limit”.
Step4 : Create the segment table with the segment number and segment address and
display it.
Step5 : Read the segment number and displacement.
Step6 : If the segment number and displacement is valid compute the real address and
display the same.
Step7 : Stop the program.
PROGRAM:
#include<stdio.h>
#include<unistd.h>
void main()
{
int b[20],l[20],n,i,pa,s,a,d; printf(“\
nProgram for segmentation”); printf(“\
nEnter the number of segments:”);
scanf(“%d”,&n);
printf(“\nEnter the base address and limit register:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&b[i]);
scanf(“%d”,&l[i])
}
printf(“\nEnter the logical address:”);
scanf(“%d”,&d);
for(i=0;i<n;i++)
{
if(i==s)
{
if(d<l[i])
{
Page 78
pa=b[i]+d;
a=b[i];
printf(“(“\n\tPageNo.\t BaseAdd. PhysicalAdd. \n\t %d \t %d \t
%d \t ”,s,a,pa);
exit(0);
}
else
{
printf(“\nPage size exceeds”);
exit(0);
}
}
}
printf(“\nInvalid
segment”);
Sample Input 1:
Program for segmentation
Enter the number of segments:3
Enter the base address and limit register:
100 50
150 20
130 34
Enter the Logical address:25
Enter the segment number:1
Sample Output 1:
PageNo. BaseAdd. PhysicalAdd.
2 130 155
Sample Input 2:
Program for segmentation
Enter the number of segments:2
Enter the Logical address and limit register:
100 50
150 20
Enter the logical address:25
Enter the segment number:1
Sample Output 2:
page size exceeds
RESULT:
Thus the program for implementing the segmentation concept was executed and the output was verified
successfully.
Page 79