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

Operating System

The document outlines the procedures for installing Windows 7 and Windows 10 operating systems, detailing system requirements and step-by-step installation processes. It also includes a section on basic UNIX commands and shell programming, providing syntax and examples for commands like date, calendar, echo, and file management. The document serves as a guide for both Windows installation and UNIX command execution.

Uploaded by

c.muthupriya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Operating System

The document outlines the procedures for installing Windows 7 and Windows 10 operating systems, detailing system requirements and step-by-step installation processes. It also includes a section on basic UNIX commands and shell programming, providing syntax and examples for commands like date, calendar, echo, and file management. The document serves as a guide for both Windows installation and UNIX command execution.

Uploaded by

c.muthupriya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Ex.No.

1 Installation of windows operating system


Date:

AIM :
To write a procedure to install Windows Operating System

Installing Windows7 Operating System:

System Requirements

If you are currently running Windows Vista, the good news is that you are ready for Windows 7. Tests performed
by various parties have consistently confirmed that Windows 7 outperformed Windows Vista on a similar
hardware configuration.

If you are coming from previous versions of Windows (pre-Vista), take note of the following suggested hardware
requirements:

 1 GHz or faster 32-bit or 64-bit processor


 1 GB RAM (for 32-bit) or 2 GB RAM (for 64-bit)
 16 GB of available disk space (for 32-bit) or 20 GB of available disk space (for 64-bit)
 DirectX 9 graphics device with Windows Display Driver Model 1.0 or higher (for Aero—the graphical
user interface and default theme in most editions of Windows 7)

Installing Windows 7

If you are currently running Windows Vista (with Service Pack 1), you can upgrade to Windows 7 directly from
within Vista. Windows XP users will need to install a fresh copy of Windows 7.

The following steps will walk you through the process of installing Windows 7 on a fresh computer.

Installing Windows 7 is straightforward—if you’re doing a clean install, simply boot up your computer with the
Windows 7 installation DVD inside the DVD drive and instruct your computer to boot from the DVD (you may
need to press a key, such as F11 or F12, while the computer is starting to enter the boot selection screen). If
you’re upgrading, simply boot into Windows Vista, insert the disc, and run the installer (if you are using Windows
XP, see the previous sidebar ).

When the installer has booted up, you will be greeted with the screen shown in Figure 1(the upgrade screen is
slightly different; you will have an option to check the compatibility of your system or start the installation). You
will be asked to select the language to install, the time and currency format, and your keyboard type
Fig 1:Installing Windows 7: the first step

With the selections made, you can now install Windows 7 by clicking the “Install now” button (see Figure 1-3).

You will be asked to accept the license agreement. (If you are upgrading, you’ll first have the option to go
online to get any updates to the installer first.) Check the licensing checkbox and continue.
Fig.2 .Click the “Install now” button to start the Windows 7 installation process

On the next screen, you have a choice between upgrading your existing Windows or installing a fresh copy of
Windows. If you are using Windows XP or earlier, the first option will not work for you—select the Custom
(advanced) option

On the next screen, you have a choice between upgrading your existing Windows or installing a fresh copy of Windows.
If you are using Windows XP or earlier, the first option will not work for you—select the Custom (advanced) option

For a fresh installation, you will be asked to select a disk for installing Windows 7. Select the appropriate disk and click
Next (see Figure 3). If you are upgrading, the Windows 7 installer will generate a compatibility report and save it to your
desktop.
Fig.3. Selecting the disk for installing Windows 7

Windows will now take some time to copy all the files into the selected disk and proceed with the installation
(see Figure 4). This will take about 20–30 minutes, depending on the speed of your computer.
Fig 4 . Windows 7 proceeding with the installation

When the installation is complete, Windows 7 will restart. After Windows 7 has been restarted, you should see the screen
shown in Figure 1-7. Provide a username; your computer name will be created based on what you have entered (you can
change it to another name if you want to after the installation). Click Next.
Fig 5 .Click the “Install now” button to start the Windows 7 installation process

On the next screen, you have a choice between upgrading your existing Windows or installing a fresh copy of
Windows. If you are using Windows XP or earlier, the first option will not work for you—select the Custom
(advanced) opti

on

Installing Windows 10 Operating System:

1. Check your device meets the Windows 10 system requirements. Below you’ll find the minimum specs
needed to run Windows 10, so check your device is capable:

CPU: 1GHz or faster processor


RAM: 1GB for Windows 10 32-bit or 2GB for Windows 10 64-bit
Storage: 32GB of space or more
GPU: DirectX 9 compatible or later with WDDM 1.0 driver
Display: 800x600 resolution or higher

2. Create USB installation media. Visit Microsoft's Windows 10 download page (opens in new tab) and select
“Download tool now” under the “create Windows 10 installation media” section. Transfer the downloaded
installer tool to a USB drive.
3. Run the installer tool. Open the installer tool by clicking on it. Accept Microsoft’s terms, and then select
“Create installation media for another PC” on the “What do you want to do?” page. After selecting which
language you want Windows 10 to run in, and which edition you want as well (32-bit or 62-bit), you’ll be
asked what type of media you want to use.

Installing from a USB drive is definitely the preferred option but you can also install from a CD or ISO file.
Once you choose your device, the installer tool will download the required files and put them onto your drive.

4. Use your installation media. Insert your installation media into your device and then access the
computer’s BIOS or UEFI. These are the systems that allow you to control your computer’s core hardware.

The process of accessing these systems is unique to each device, but the manufacturer’s website should be able
to give you a helping hand here. Generally, you'll need to press the F2, F12 or Delete keys as your computer
boots up.

5. Change your computer's boot order. Once you have access to your computer’s BIOS/UEFI you’ll need to
locate the settings for boot order. You need the Windows 10 installation tool to be higher up on the list than the
device’s current current boot drive: this is the SSD or HDD that your existing OS is stored on. You should
move the drive with the installer files to the very top of the boot order menu. Now, when you restart your
device the Windows 10 installer should load up first.

6. Restart your device. Save your settings in the BIOS/UEFI and reboot your device.

7. Complete the installation. Your device should now load up the Windows 10 installation tool on restart.
This will guide you through the rest of the installation process.
Ex.No .2 Illustration of UNIX commands and Shell Programming

Ex.No:2.1
BASICS OF UNIX COMMANDS
Date:

AIM :
To study and execute the commands in unix.
COMMAND:
1. Date Command:
This command is used to display the current data and time.
Syntax :
$date -options
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”
Output:
16-24-19

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>
Here the first syntax gives the entire calendar for given year & the second Syntax gives the calendar of
reserved month of that year.
Output:

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
To have the output in different line, the following command can be used.
Syntax : $echo “text
>line2
>line3”
Input &Output:
[cse35@localhost ~]$ echo "Hello
> how
>r
> u"
Hello
how
r
u
4.’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.
Input &Output:
[cse35@localhost ~]$ who
cse35 pts/1 2017-12-28 16:06 (172.16.10.123)
[cse35@localhost ~]$ who -H
NAME LINE TIME COMMENT
cse35 pts/1 2017-12-28 16:06 (172.16.10.123)
[cse35@localhost ~]$ who -b
system boot 2017-12-28 16:03
5.’who am i’ Command :
Display the details of the current working directory.
Syntax : $who am i
Input &Output:
[cse35@localhost ~]$ who am i
cse35 pts/1 2017-12-28 16:06 (172.16.10.123)
6.’tty’ Command :
It will display the terminal name.
Syntax : $tty

7.’Binary’ Calculator Command:

Use bc is to enter the calculator’s own shell.We can run many calculations in a row.
$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

Now we can type in calculations or commands, one per line:

1+1
OUTPUT:
2
Input2:
(4+7)*2
4+7*2

8.’CLEAR’ Command:
It is used to clear the screen.
Syntax : $clear

9.’MAN’ Command:
It helps us to know about the particular command and its options & working. It is like “help command in
windows.
Syntax : $man <command name>

10. tput Command:


The tput command uses the terminfo database to make terminal-dependent information available to the shell.
The tput command outputs a string if the attribute CapabilityName is of type string. The output string is an integer if the
attribute is of type integer. If the attribute is of type Boolean, the tput command sets the exit value (0 for TRUE, 1 for
FALSE), and produces no other output.
Syntax : $tput <argument>

XTERM DESCRIPTION LIMITATION

The xterm terminal description in the DEC.TI file on AIX® Version 4 provides underline mode by using the
SGR attribute. The SMUL and RMUL attributes are not currently defined in the XTERM terminal description
on AIX Version 4. Use the more generic capability named SGR("Select Graphic Rendition", which is also
known as "Set Attribute".)

tput sgr x y

Where x is either a 1 or a 0 to turn standout mode on or off respectively, and y is either a 1 or a 0 to turn
underline mode on or off respectively. See the article "terminfo file format" for more details on the SGR
capability.

tput sgr 0 1 turn off standout; turn on underline


tput sgr 0 0 turn off standout; turn off underline
tput sgr 1 1 turn on standout; turn on underline
tput sgr 1 0 turn on standout; turn off underline

.
Output:
11. 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 columnwise.
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.
Input &Output:
[cse35@localhost ~]$ ls
aaa ff fff
[cse35@localhost ~]$ ls -a
. aaa .bash_logout .bashrc ff .gnome2
.. .bash_history .bash_profile .emacs fff .zshrc
[cse35@localhost ~]$ ls -c
ff fff aaa
[cse35@localhost ~]$ ls -d
.
[cse35@localhost ~]$ ls -m
aaa, ff, fff
[cse35@localhost ~]$ ls -p
aaa/ ff fff/
[cse35@localhost ~]$ ls -r
fff ff aaa
[cse35@localhost ~]$ ls -f
.emacs .bash_profile ff .bash_logout fff .gnome2
.bashrc .. . aaa .bash_history .zshrc
[cse35@localhost ~]$ ls -x
aaa ff fff
[cse35@localhost ~]$

DIRECTORY RELATED COMMANDS:

1. Present Working Directory Command :


To print the complete path of the current working directory.
Syntax : $pwd
Input &Output:
[cse35@localhost ~]$ pwd
/home/cse35

2. MKDIR Command :
To create or make a new directory in a current directory.
Syntax : $mkdir <directory name>
Input &Output:
[cse35@localhost ~]$ mkdir folder1

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

4. RMDIR Command :
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.
Type ‘Ctrl-d’ at the end to save the file.

2. DISPLAY A FILE:
To display the content of file mentioned we use CAT command without “>” operator.
Syntax :
$cat filename
Input &Output:
[cse35@localhost ~]$
[cse35@localhost ~]$ cat >example2
hi
hello
this is cat command file
[cse35@localhost ~]$ cat example2
hi
hello
this is cat command file

3. COPYING CONTENTS:
To copy the content of one file with another. If file does not 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.
Input &Output:
[cse35@localhost ~]$ cat example2>>example3
[cse35@localhost ~]$ cat example3
hi
hello
this is cat command file
[cse35@localhost ~]$ cat example2
hi
hello
this is cat command file

4. SORTING A FILE:
To sort the contents in alphabetical order in reverse order.
Syntax :
$sort <filename >
Input &Output:
[cse35@localhost ~]$ sort example2
hello
hi
this is cat command file

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>
Output:
[cse35@localhost ~]$ cat example2
hi
hello
this is cat command file
[cse35@localhost ~]$ cp example2 example4
[cse35@localhost ~]$ cat example4
hi
hello
this is cat command file
[cse35@localhost ~]$
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>
Output:
[cse35@localhost ~]$ cat >yy.txt
This is my first file
created for copy content
thankyou
[cse35@localhost ~]$ cat yy.txt
This is my first file
created for copy content
thankyou
[cse35@localhost ~]$ mv yy.txt xx.txt
[cse35@localhost ~]$ cat yy.txt
cat: yy.txt: No such file or directory
[cse35@localhost ~]$ cat xx.txt
This is my first file
created for copy content
thankyou
7. REMOVE Command:

Use the rm command to remove files you no longer need. The rm command removes the entries for a
specified file, group of files, or certain select files from a list within a directory. User confirmation, read
permission, and write permission are not required before a file is removed when you use the rm
command.
Syntax :
$rm <filename>
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.
Input &Output:
[cse35@localhost ~]$ cat xx.txt
This is my first file
created for copy content
thankyou
[cse35@localhost ~]$ wc xx.txt
3 10 56 xx.txt
9. LINE PRINTER:

submits files for printing or alters a pending job.


Syntax :
$lp <filename>
10. PAGE Command:
This command is used to display the contents of the file page wise & next page can be viewed by 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 screen full 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: The grep filter searches a file for a particular pattern of characters, and displays all lines that contain
that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for
global search for regular expression and print out).

Syntax:

grep [options] pattern [files]

Options Description

-c : This prints only a count of the lines that match a pattern


-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

-A n : Prints searched line and nlines after the result.


-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.

$cat > geekfile.txt

unix is great os. unix was developed in Bell labs.


learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

$grep -i "UNix" geekfile.txt


Output:

unix is great os. unix was developed in Bell labs.


Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

Case insensitive search : The -i option enables to search for a string case insensitively in the given file. It
matches the words like “UNIX”, “Unix”, “unix”.

PIPE: It is a mechanism by which the output of one command can be channeled into the input of another command.
A pipe is a form of redirection (transfer of standard output to some other destination) that is used in Linux and
other Unix-like operating systems to send the output of one command/program/process to another
command/program/process for further processing.
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]”
WC: Word Command.Used to list the no of lines,words,characters
Syntax: $wc <filename>
COMMUNICATION THROUGH UNIX COMMANDS

1. MESG
Description: Mesg controls the access to your terminal by others. It’s typically used to allow or disallow other users to
write to your terminal (see write(1)).

OPTIONS
Tag Description

y Allow write access to your terminal.

n Disallow write access to your terminal.

If no option is given, mesg prints out the current access state of your terminal.
Syntax: $mesg y
Input & Output:
[cse35@localhost ~]$ mesg
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, which 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>
Ex.No:2.2 SHELL PROGRAMMING

DATE : Study of Unix shell Programming

AIM:

To study about 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.
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 [ ]
are used 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 any process 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 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
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) 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.
2.if…else
Syntax :
If cp $ source $ target
Then
Echo File copied successfully
Else
Echo Failed to copy the file.
3.nested if
here sequence of condition are checked and the corresponding
performed accordingly.
Syntax :
if condition
then
command
if condition
then
command
else
command
fi

4.case ….. esac


This construct helps in execution of the shell script based on
Choice.
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 ;;
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
--------------------------------------
do
block of statements
done
------------
until control command
do
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 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
Command substitution To assign the output of a UNIX/Linux command to a variable, or use the output of a
command in a string, backquotes are used.
EXAMPLE
variable_name=`command` 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
or
$./sum.sh
Ex.No:2.3 SHELL PROGRAMMING

DATE : CONCATENATION OF TWO STRINGS

Aim:
To write 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: CONCATENATION OF TWO STRINGS

echo “enter the first string”


read str1
echo “enter the second string”
read str2
echo “the concatenated string is” $str1$str2

Input:
Enter first string: Hello
Enter first string: World

Output:
The concatenated string is HelloWorld
Ex.No:2.4 SHELL PROGRAMMING

COMPARISON OF TWO STRINGS


DATE :

Aim:
To write 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
INPUT:

Enter first string: hello

Enter second string: hello

OUTPUT:

The two strings are equal

INPUT:

Enter first string: hello

Enter second string: helo

OUTPUT:

The two strings are not equal


Ex.No:2.5 SHELL PROGRAMMING

DATE : MAXIMUM OF THREE NUMBERS

Aim:
To write a shell program to find greatest of three numbers.

Algorithm:
Step1: Declare the three variables.
Step2: Check if A is greater than B and C.
Step3: If so print A is greater.
Step4: Else check if B is greater than C.
Step5: If so print B is greater.
Step6: Else print C is greater.

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

INPUT:

Enter A:23

Enter B:45

Enter C:67

OUTPUT:

C is greater
Ex.No:2.6 SHELL PROGRAMMING

DATE : FIBONACCI SERIES

Aim:
To write a shell program to generate fibonacci series.

Algorithm :
Step 1 : Initialize a to 0 and b to 1.
Step 2 : Print the values of 'a' and 'b'.
Step 3 : Add the values of 'a' and 'b'. Store the added value in variable 'c'.
Step 4 : Print the value of 'c'.
Step 5 : Initialize 'a' to 'b' and 'b' to 'c'.
Step 6 : Repeat the steps 3,4,5 till the value of 'a' is less than 10

PROGRAM :

clear
echo "How many number of terms to be generated ?"
read n
x=0
y=1
i=2
echo "Fibonacci Series up to $n terms :"
echo "$x"
echo "$y"
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done

INPUT:

How many number of terms to be generated?

5
OUTPUT:

Fibonacci Series up to 5 terms :

3
Ex.No:2.7 SHELL PROGRAMMING

DATE : ARITHMETIC OPERATIONS USING CASE

Aim:
To write a shell program to perform the arithmetic operations using case

Algorithm :

Step 1 : Read the input variables and assign the value

Step 2 : Print the various arithmetic operations which we are going to perform

Step 3 : Using the case operator assign the various functions for the arithmetic

operators.

Step 4 : Check the values for all the corresponding operations.

Step 5 : Print the result and stop the execution.

PROGRAM:

echo "Enter Two Numbers"


read a b
echo "What do you want to do? (1 to 5)"
echo "1) Sum"
echo "2) Difference"
echo "3) Product"
echo "4) Quotient"
echo "5) Remainder"
echo "Enter your Choice"
read n
case "$n" in
1) echo "The Sum of $a and $b is `expr $a + $b`";;
2) echo "The Difference between $a and $b is `expr $a - $b`";;
3) echo "The Product of the $a and $b is `expr $a \* $b`";;
4) echo "The Quotient of $a by $b is `expr $a / $b`";;
5) echo "The Remainder of $a by $b is `expr $a % $b`";;
esac
INPUT1:
Enter Two Numbers
34
What do you want to do? (1 to 5)
1) Sum
2) Difference
3) Product
4) Quotient
5) Remainder
Enter your Choice
1

OUTPUT1:
The Sum of 3 and 4 is 7

INPUT2:
Enter Two Numbers
34
What do you want to do? (1 to 5)
1) Sum
2) Difference
3) Product
4) Quotient
5) Remainder
Enter your Choice
2

OUTPUT2:
The Difference between 3 and 4 is -1
Ex.No:2.7 SHELL PROGRAMMING

DATE : PROGRAM TO FIND ODD OR EVEN

Aim:
To write a shell program to find Odd or Even

Algorithm :

Step 1: Start the Program

Step 1 : Read the input variables and get the number as input number ‘n’

Step 2 : Find the mod value of the input number ‘n’ with 2.

Step 3 : If the remainder is 0 means then the number is even number else the number is odd number

Step 4 : Print the result and stop the execution

PROGRAM:

echo -n "Enter number : "


read n
rem=$(( $n % 2 ))
if [ $rem -eq 0 ]
then
echo "$n is even number"
else
echo "$n is odd number"
fi

OUTPUT:

Enter number : 3

3 is odd number
Ex.No:2.8 SHELL PROGRAMMING

DATE : PROGRAM TO FIND FACTORIAL OF A NUMBER

Aim:
To write a shell program to find a factorial a number

Algorithm :

Step 1. Get a number

Step 2. Use for loop or while loop to compute the factorial by using the below formula

Step 3. fact(n) = n * n-1 * n-2 * .. 1

Step 4. Display the result.

PROGRAM

fact ()
{
if [ $1 -gt 1 ]; then
y=`expr $1 - 1`
fact $y
x=$(( $1 * $? ))
return $x
else
return 1
fi
}

echo -e "Enter a number : \c"


read num
fact $num
echo "Factorial of $num is $?."

OUTPUT:
Enter a number: 4

Factorial of 4 is 24.
3. Process Management using System Calls : Fork, Exit, Getpid, Wait, Close
Ex.No:3.1
Program to simulate Opendir() and readdir() System Call
DATE :

AIM:

To write a program to simulate Opendir () and readdir () system call

ALGORITHM:

1.Start the Program


2.Create a directory
3.Open the directory with opendir() System call
4.If the required directory is not found then display the directory is not found.
5.Else read the directory with the System call readdir()
6.Stop the program.

PROGRAM:
sample.c
#include<stdio.h>
#include<dirent.h>
int main()
{
char dirname[10];
DIR*p;
struct dirent *d;
printf("Enter directory name:\n");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find directory");
exit(-1);
}
while(d=readdir(p))
printf("%s\n",d->d_name);
return 0;
}
OUTPUT:
[cse2@localhost]$ mkdir bhu
[cse2@localhost]$cd bhu
[cse2@localhost bhu]$cat >first.txt
Hi
Hello
How r u
[cse2@localhost bhu]$cd
[cse2@localhost ]$ cc sample.c
[cse2@localhost]$./a.out
Enter directory name:
bhu
..
first.txt
Ex.No:3.2
Program to simulate fork() System call
DATE :

AIM: To write a C Program to implement fork() System call.


ALGORITHM:
1.Start the Program
2.Create child process
3.Get the pid value and print the child process id
4.Exit the Program to terminate the current running process using exit() System call.
5.Stop the Program.

Program: fork() System call


#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("I am: %d\n", (int) getpid());
pid_t pid = fork();
printf("fork returned: %d\n", (int) pid);

if (pid < 0) { /* error occurred */


perror("Fork failed");
}
if (pid == 0) { /* child process */
printf("I am the child with pid %d\n", (int) getpid());
printf("Child process is exiting\n");
exit(0);
}
/* parent process */
printf("I am the parent waiting for the child process to end\n");
wait(NULL);
printf("parent process is exiting\n");
return(0);
}

OUTPUT:
Ex.No:3.3
Program to simulate wait() System call
DATE :

AIM: To write a C Program to implement wait() System call.


ALGORITHM:

 If any process has more than one child processes, then after calling wait(),
parent process has to be in wait state if no child terminates.
 If only one child process is terminated, then return a wait() returns process ID
of the terminated child process.
If more than one child processes are terminated than wait() reap any
arbitrarily child and return a process ID of that child process.
 When wait() returns they also define exit status (which tells our, a process
why terminated) via pointer, If status are not NULL.
If any process has no child process then wait() returns immediately “-1”
Program:
// C program to demonstrate working of wait()
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
int main()
{
pid_t cpid;
if (fork()== 0)
exit(0); /* terminate child */
else
cpid = wait(NULL); /* reaping parent */
printf("Parent pid = %d\n", getpid());
printf("Child pid = %d\n", cpid);
return 0;
}

OUTPUT:
Parent pid = 12345678
Child pid = 89546848
4.Implementation of the various CPU Scheduling Algorithms
Ex.No:4.1
Implementation of FCFS Scheduling
DATE :

AIM:
To write a C program to implement the CPU scheduling algorithm for FIRST COME FIRST
SERVE.

ALGORITHM:
Step1: Create the number of process.
Step2: Get the ID and Service time for each process.
Step3: Initially, Waiting time of first process is zero and Total time for the first
process is the starting time of that process.
Step4: Calculate the Total time and Processing time for the remaining processes.
Step5: Waiting time of one process is the Total time of the previous process.
Step6: Total time of process is calculated by adding Waiting time and Service time.
Step7: Total waiting time is calculated by adding the waiting time for lack process.
Step8: Total turn around time is 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 time by the
number of process.
Step11: Display the result

PROGRAM-FCFS Scheduling

#include<stdio.h>
#include<string.h>
int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);

printf("\nEnter Process Burst Time\n");


for(i=0;i<n;i++)
{
printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
}

wt[0]=0; //waiting time for first process is 0


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}

printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");

for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
}
avwt/=i;
avtat/=i;
printf("\n\nAverage Waiting Time:%d",avwt);
printf("\nAverage Turnaround Time:%d",avtat);
return 0;
}

OUTPUT:
Ex.No:4.2
Implementation of SJF Scheduling
DATE :

AIM:
To write a C program to implement the CPU scheduling algorithm for Shortest job first.

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 turnaround 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 turnaround time by dividing the total waiting time by
total number of process.
Step11: Display the result

PROGRAM:-SJF Scheduling
#include<stdio.h>
#include<string.h>
void main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);

printf("\nEnter Burst Time:\n");


for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}

//sorting burst time in ascending order using selection sort


for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting time for first process will be zero

//calculate waiting time


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n; //average waiting time


total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=(float)total/n; //average turnaround time


printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}
OUTPUT:
Ex.No:4.3
Implementation of Priority Scheduling
DATE :

AIM:
To write a C program to implement CPU scheduling algorithm for priority scheduling.

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:-Priority Scheduling
#include<stdio.h>
#include<string.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);

printf("\nEnter Burst Time and Priority\n");


for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1; //contains process number
}

//sorting burst time, priority and process number in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}
temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting time for first process is zero

//calculate waiting time


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=total/n; //average waiting time


total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=total/n; //average turnaround time


printf("\n\nAverage Waiting Time=%d",avg_wt);
printf("\nAverage Turnaround Time=%d\n",avg_tat);

return 0;
}
OUTPUT:
Ex.No:4.4
Implementation of Round Robin Scheduling
DATE :

AIM :
To write a C program to simulate the CPU scheduling algorithm for round robin

ALGORITHM:

a. Start
b. Take input the number of processes in the system (NOP) from the user.
c. For each process, take input its arrival time and burst time from the user and store it in the respective
arrays.
d. Take input the time quantum for the process from the user.
e. Set y = NOP to track the number of processes that are not yet completed.
f. Initialize sum, count, wt and tat to zero.
g. Display the table headers with column names: Process No, Burst Time, TAT, and Waiting Time.
h. While there are processes that are not yet completed (y > 0), do the following:

1. Check if the remaining burst time of the current process (temp[i]) is less than or equal to the time
quantum and greater than zero. If yes, execute the process for the remaining burst time and add the sum
of burst times to the variable sum. Set the remaining burst time of the current process to zero and set
count to 1. b.
2. If the remaining burst time of the current process is greater than zero, execute the process for the time
quantum and add the time quantum to the variable sum. Reduce the remaining burst time of the current
process by the time quantum. c.
3. If the remaining burst time of the current process is zero and count is 1, mark the process as completed,
reduce the number of processes that are not yet completed (y), and calculate the waiting time and
turnaround time of the completed process. Add the waiting time to the variable wt and the turnaround
time to the variable tat. Display the details of the completed process in the table.
4. . Check if the current process is the last process in the queue. If yes, set i to zero. Else, check if the
arrival time of the next process in the queue is less than or equal to the current sum of burst times. If
yes, set i to the index of the next process. Else, set i to zero.

i.Calculate the average waiting time (avg_wt) and average turnaround time (avg_tat) using the formulas:
avg_wt = wt * 1.0 / NOP avg_tat = tat * 1.0 / NOP
j. Display the average waiting time and average turnaround time.
k. End.
Program: Round Robin

#include<stdio.h>
int main()
{
int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];
float avg_wt, avg_tat;
printf(" Total number of process in the system: ");
scanf("%d", &NOP);
y = NOP; // Assign the number of process to variable y

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


{
printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);
printf(" Arrival time is: \t");
scanf("%d", &at[i]);
printf(" \nBurst time is: \t");
scanf("%d", &bt[i]);
temp[i] = bt[i];
}
printf("Enter the Time Quantum for the process: \t");
scanf("%d", &quant);
printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");
for(sum=0, i = 0; y!=0; )
{
if(temp[i] <= quant && temp[i] > 0)
{
sum = sum + temp[i];
temp[i] = 0;
count=1;
}
else if(temp[i] > 0)
{
temp[i] = temp[i] - quant;
sum = sum + quant;
}
if(temp[i]==0 && count==1)
{
y--;
printf("\nProcess No[%d] \t\t %d\t\t\t\t %d\t\t\t %d", i+1, bt[i], sum-at[i], sum-at[i]-bt[i]);
wt = wt+sum-at[i]-bt[i];
tat = tat+sum-at[i];
count =0;
}
if(i==NOP-1)
{
i=0;
}
else if(at[i+1]<=sum)
{
i++;
}
else
{
i=0;
}
}
avg_wt = wt * 1.0/NOP;
avg_tat = tat * 1.0/NOP;
printf("\n Average Waiting Time: \t%f", avg_wt);
printf("\n Average Turnaround Time: \t%f", avg_tat);
return 0;
}
OUTPUT:
Ex.No.5 Inter process communication strategy

Ex.No:5.1
Implementation of Shared Memory IPC
DATE :

Aim:
To write a c program to develop an application using Inter process Communication (IPC) using shared memory
IPC
Algorithm:
SERVER:

1. Define a character variable c.


2. Define an integer variable shmid to store the shared memory ID.
3. Define a key_t variable key and set it to 2013.
4. Define a character pointer variable shm and a char pointer variable s.
5. Use the shmget() function to create a shared memory segment with the key and size specified in
shmsize. If shmget() returns a negative value, output an error message using perror() and exit the
program using exit(1).
6. Print the shared memory ID using printf().
7. Use the shmat() function to attach the shared memory segment. If shmat() returns a negative value,
output an error message using perror() and exit the program using exit(1).
8. Use memset() to set the shared memory to 0.
9. Set s equal to shm.
10. Use a for loop to write the characters 'a' through 'z' onto the shared memory, incrementing s each time.
11. Add a null character at the end of the shared memory.
12. Use a while loop to wait for the client to finish reading the shared memory by checking if the first
character of the shared memory is equal to '*'.
13. Print a message indicating that the client has finished reading.
14. Use shmdt() to detach the shared memory. If shmdt() returns a non-zero value, output an error
message using fprintf().
15. Use shmctl() to remove the shared memory segment.

CLIENT:
1. Define an integer variable shmid to store the shared memory ID.
2. Define a key_t variable key and set it to 2013.
3. Define a character pointer variable shm and a character pointer variable s.
4. Use the shmget() function to get the shared memory segment with the key and size specified in shmsize.
If shmget() returns a negative value, output a message indicating that the server is not started using
printf() and exit the program using exit(1).
5. Print the shared memory ID using printf().
6. Use the shmat() function to attach the shared memory segment. If shmat() returns a negative value,
output an error message using perror() and exit the program using exit(1).
7. Use a for loop to read the characters from the shared memory and print them to the screen, incrementing
s each time.
8. Add a newline character to the end of the output.
9. Set the first character of the shared memory to '*' to indicate that the client has finished reading.
10. Use shmdt() to detach the shared memory. If shmdt() returns a non-zero value, output an error message
using fprintf().
PROGRAM:-Shared Memory IPC
SERVER:
#include <stdio.h>
#include <stdlib.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27
int main()
{
char c;
int shmid;
key_t key = 2013;
char *shm, *s;
if ((shmid = shmget(key, shmsize, IPC_CREAT|0666)) < 0)
{
perror("shmget");
exit(1);
}
printf("Shared memory id : %d\n", shmid);
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
memset(shm, 0, shmsize);
s = shm;
printf("Writing (a-z) onto shared memory\n");
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s = '\0';
while (*shm != '*');
printf("Client finished reading\n");
if(shmdt(shm) != 0)
fprintf(stderr, "Could not close memory segment.\n");
shmctl(shmid, IPC_RMID, 0);
return 0;
}
CLIENT:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27
int main()
{
int shmid;
key_t key = 2013;
char *shm, *s;
if ((shmid = shmget(key, shmsize, 0666)) < 0)
{
printf("Server not started\n");
exit(1);
}
else
printf("Accessing shared memory id : %d\n",shmid);
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
printf("Shared memory contents:\n");
for (s = shm; *s != '\0'; s++)
putchar(*s);
putchar('\n');
*shm = '*';
return 0;
}
OUTPUT:
SERVER:
[2cs254@cc5 ~]$ vi sserver.c
[2cs254@cc5 ~]$ cc sserver.c
[2cs254@cc5 ~]$ ./a.out
Shared memory id : 458756
Writing (a-z) onto shared memory
Client finished reading

CLIENT:
[2cs254@cc5 ~]$ vi client.c
[2cs254@cc5 ~]$ cc client.c
[2cs254@cc5 ~]$ ./a.out
shared memory id:458756
shared memory contents:
abcdefghijklmnopqurstuvwxyz
Ex.No:6
Implementation of mutual exclusion by Semaphore
DATE :

AIM:
To write a C program to implement the Producer & consumer Problem (Semaphore)

ALGORITHM:
Step 1: The Semaphore mutex, full & empty are initialized.

Step 2: In the case of producer process

i) Produce an item in to temporary variable.

ii) If there is empty space in the buffer check the mutex value for enter into the critical section.

iii) If the mutex value is 0, allow the producer to add value in the temporary variable to the buffer.

Step 3: In the case of consumer process

i) It should wait if the buffer is empty

ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove item from buffer

iii) Signal the mutex value and reduce the empty value by 1.

iv) Consume the item.

Step 4: Print the result


PROGRAM:

#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
int producer();
int consumer();
int wait(int);
int signal(int);
printf("\n1.Producer \n2.Consumer \n3.Exit\n");
while(1)
{
printf("\n Enter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
else
printf("\n Buffer is Full\n");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf("\n Buffer is Empty\n");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return(++s);
}
producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\n Producer Produces the item%d\n",x);
mutex=signal(mutex);
}
consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\n Consumer consumes item%d\n",x);
x--;
mutex=signal(mutex);
}
OUTPUT:

[2cs163@cc5]$ vi semaphore.c

[2cs163@cc5]$ cc semaphore.c

[2cs163@cc5]$ ./a.out

1.Producer

2.Consumer

3.Exit

Enter your choice

Producer Produces the item1

Enter your choice

Consumer consumes item1

Enter your choice

[2cs163@cc5 ~]$ ./a.out

1.Producer

2.Consumer

3.Exit

Enter your choice

Buffer is Empty

Enter your choice

3
Ex.No:7
Bankers algorithm for deadlock avoidance
DATE :

AIM:
To implement the banker’s algorithm for Dead Lock Avoidance.

ALGORITHM:

1. Initialize the number of processes (n) and number of resources (m).


2. Initialize the allocation matrix (alloc), maximum matrix (max), and available resources (avail).
3. Initialize the finish array (f) and answer array (ans) to all 0's.
4. Initialize the index (ind) to 0.
5. Initialize the need matrix by subtracting the allocation matrix from the maximum matrix.
6. Loop through all processes k from 0 to n-1.
7. Loop through all processes i from 0 to n-1.
8. Check if process i is not already finished (f[i] == 0).
9. If process i is not finished, loop through all resources j from 0 to m-1.
10. Check if the need of process i for resource j is greater than the available resources for that resource
(need[i][j] > avail[j]).
11. If the need of process i for resource j is greater than the available resources for that resource, set flag to
1 and break out of the loop.
12. If the loop completes without setting flag to 1, add process i to the answer array (ans[ind] = i) and
increment the index (ind).
13. Update the available resources by adding the allocation matrix for process i to the available resources.
14. Mark process i as finished (f[i] = 1).
15. If all processes have been checked and no process can be added to the answer array, the system is not
safe.
16. Otherwise, print the safe sequence by looping through the answer array and printing each process in
order.

17.End of program.
PROGRAM:-Bankers Deadlock Avoidance
// Banker's Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix


{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

int flag = 1;

for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
}
}

if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);

OUT PUT:
P1 -> P3 -> P4 -> P0 -> P2
Ex.No:8
Implementation of Deadlock Detection Algorithm
DATE :

AIM:

To write a C Program to implement deadlock Detection technique.


ALGORITHM:

1. Start the program.

2. Get the values of resources and processes.

3. Get the avail value.

4. After allocation find the need value.

5. Check whether it’s possible to allocate.

6. If it is possible then the system is in safe state.

7. Else system is not in safety state

8. Stop the process.

PROGRAM:Deadlock Detection

#include <stdio.h>
#include <stdbool.h>
#define N 5
#define M 3

int main()
{
int allocation[N][M] = {{0, 1, 0},
{2, 0, 0},
{0, 0, 2},
{1, 1, 0},
{0, 0, 2}};

int max[N][M] = {{1, 1, 1},


{2, 0, 0},
{0, 0, 2},
{1, 2, 0},
{2, 2, 2}};

int available[M] = {0, 0, 0};


int need[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}

bool finished[N] = {false};


bool deadlock = true;

while (deadlock) {
deadlock = false;

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


if (!finished[i]) {
bool can_run = true;

for (int j = 0; j < M; j++) {


if (need[i][j] > available[j]) {
can_run = false;
break;
}
}

if (can_run) {
finished[i] = true;

for (int j = 0; j < M; j++) {


available[j] += allocation[i][j];
}
}
}
}

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


if (!finished[i]) {
bool can_run = true;

for (int j = 0; j < M; j++) {


if (need[i][j] > available[j]) {
can_run = false;
break;
}
}
if (can_run) {
deadlock = true;
printf("Deadlock detected in process P%d\n", i);
break;
}
}
}
}

return 0;
}

OUTPUT:
Deadlock detected in process P0
Ex.No:9

DATE : Implementation of Threading & Synchronization Applications

Aim:
The program for implementing the threading and synchronization applications

Algorithm:
1. Start the program
2. Create two threads
3. Start the first thread and process the thread
4. Stop the first thread working
5. Start the second thread and process the 2nd thread
6. Stop the second thread working
7. Print the status
8. Stop the Program

Program: Threading & Synchronization Applications

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

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

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

pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
int i = 0;
int err;

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

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

To Compile this Program,give the following command:


$] gcc filename.c –lpthread
To run that above program
$]./a.out

Output:

$ ./threads

Job 1 started
Job 1 finished
Job 2 started
Job 2 finished
Explanation:

The loop for(i=0; i<(0xFFFFFFFF);i++); in the doSomeThing function is


used to simulate a long-running task that takes some time to complete. The loop
simply iterates a very large number of times (0xFFFFFFFF, which is the
hexadecimal representation of the decimal number 4,294,967,295) without
actually doing anything in each iteration. This is done to introduce a delay
between the "started" and "finished" messages that are printed by the thread.

The pthread_mutex_init function is used to initialize a mutex object before it can be


used for synchronizing access to shared resources in a multi-threaded program.

In the code snippet you provided, the pthread_mutex_init function is used to initialize
the lock mutex object with default attributes. If the initialization fails (indicated by the
function returning a non-zero value), the program prints an error message and returns with an
exit status of 1.

It's important to initialize a mutex object before using it, as uninitialized mutexes can lead to
undefined behavior and potential race conditions in a multi-threaded program. The
pthread_mutex_init function ensures that the mutex is properly initialized and ready to
use.
10.Implementation of Threading & Synchronization Applications
Ex.No:10.1

DATE : FIFO Page Replacement

AIM: To write and execute the Program for FIFO Page Replacement Algorithm.

ALGORITHM

1. Start the process


2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Form a queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the process

PROGRAM:

#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d\n",count);
return 0;
}
OUTPUT:

ENTER THE NUMBER OF PAGES: 20

ENTER THE PAGE NUMBER : 70120304230321201701

ENTER THE NUMBER OF FRAMES :3

ref string page frames

7 7 -1 -1

0 7 0 -1

1 7 0 1

2 2 0 1

3 2 3 1

0 2 3 0

4 4 3 0

2 4 2 0

3 4 2 3

0 0 2 3

1 0 1 3

2 0 1 2

7 7 1 2

0 7 0 2

1 7 0 1

Page Fault Is 15
Ex.No:10.2

DATE : LRU Page replacement

AIM: To write and execute the Program for LRU Page Replacement Algorithm.

ALGORITHM :
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process

PROGRAM:LRU Page replacement

#include<stdio.h>
Int main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);
}
OUTPUT:

Enter no of pages:10

Enter the reference string:7 5 9 4 3 7 9 6 2 1

Enter no of frames:3

7 5

7 5 9

4 5 9

4 3 9

4 3 7

9 3 7

9 6 7

9 6 2

1 6 2

The no of page faults is 10


Ex.No:10.3

DATE : LFU Page replacement

AIM
To write and execute the Program for LFU Page Replacement Algorithm.

ALGORITHM:

1. Start the program.


2. Declare variables to hold the total number of frames, total number of pages, hit count, page values,
frame values, array values, and time values.
3. Prompt the user to enter the total number of pages and the total number of frames.
4. Initialize all the frame values to -1.
5. Initialize all the array values to 0.
6. Prompt the user to enter the reference string values.
7. For each page in the reference string, do the following: a. Increase the count of the current page in the
array. b. Set the current time for the current page. c. Set a flag to 1. d. Set the initial value of k as the
first frame value. e. For each frame in the frame array, do the following: i. If the current frame is empty
or holds the current page value, set the flag to 0, increment the hit count if the frame already holds the
current page value, and replace the current frame with the current page value. ii. If the count of k in the
array is greater than the count of the current frame value in the array, set k to the current frame value. f.
If the flag is still 1, find the frame with the minimum time value whose count matches that of k in the
array, set its count to 0, and replace it with the current page value. g. Print the current frame array.
8. Print the total hit count.
9. End the program.

PROGRAM:

#include<stdio.h>
int main()
{
int total_frames, total_pages, hit = 0;
int pages[25], frame[10], arr[25], time[25];
int m, n, page, flag, k, minimum_time, temp;
printf("Enter Total Number of Pages:\t");
scanf("%d", &total_pages);
printf("Enter Total Number of Frames:\t");
scanf("%d", &total_frames);
for(m = 0; m < total_frames; m++)
{
frame[m] = -1;
}
for(m = 0; m < 25; m++)
{
arr[m] = 0;
}
printf("Enter Values of Reference String\n");
for(m = 0; m < total_pages; m++)
{
printf("Enter Value No.[%d]:\t", m + 1);
scanf("%d", &pages[m]);
}
printf("\n");
for(m = 0; m < total_pages; m++)
{
arr[pages[m]]++;
time[pages[m]] = m;
flag = 1;
k = frame[0];
for(n = 0; n < total_frames; n++)
{
if(frame[n] == -1 || frame[n] == pages[m])
{
if(frame[n] != -1)
{
hit++;
}
flag = 0;
frame[n] = pages[m];
break;
}
if(arr[k] > arr[frame[n]])
{
k = frame[n];
}
}
if(flag)
{
minimum_time = 25;
for(n = 0; n < total_frames; n++)
{
if(arr[frame[n]] == arr[k] && time[frame[n]] < minimum_time)
{
temp = n;
minimum_time = time[frame[n]];
}
}
arr[frame[temp]] = 0;
frame[temp] = pages[m];
}
for(n = 0; n < total_frames; n++)
{
printf("%d\t", frame[n]);
}
printf("\n");
}
printf("Page Hit:\t%d\n", hit);
}
OUTPUT:
Ex.No:10.4

DATE : Optimal Page replacement

AIM:
To write and execute the Program for Optimal Page Replacement Algorithm.

ALGORITHM:

1. Start the program.


2. Declare variables to hold the total number of pages, page values, frame values, count of page in frame,
fault count, distance, and other temporary variables.
3. Prompt the user to enter the total number of pages and the page sequence values.
4. Prompt the user to enter the frame size.
5. Initialize the count and frame arrays to 0 and -1 respectively.
6. For each page in the page sequence, do the following: a. Set a flag to 0 and the temporary variable to
the current page value. b. For each frame in the frame array, do the following: i. If the current page is
already in the frame, set the flag to 1 and break the loop. ii. If the current frame is empty, set the current
page value to the current frame, increment the fault count, and break the loop. c. If the flag is still 0 and
the frame array is not full, set the current page value to the next empty frame, increment the fault count,
and increment the frame index. d. If the flag is still 0 and the frame array is full, do the following: i. For
each frame in the frame array, calculate the distance from the current page to the next occurrence of the
current frame in the page sequence. ii. Find the frame with the maximum distance and replace it with
the current page value. iii. Increment the fault count. e. Print the current page and frame array.
7. Print the total fault count.
8. End the program.

PROGRAM:
#include<stdio.h>
int main()
{
int n,pg[30],fr[10];
int count[10],i,j,k,fault,f,flag,temp,current,c,dist,max,m,cnt,p,x;
fault=0;
dist=0;
k=0;
printf("Enter the total no pages:\t");
scanf("%d",&n);
printf("Enter the sequence:");
for(i=0;i<n;i++)
scanf("%d",&pg[i]);
printf("\nEnter frame size:");
scanf("%d",&f);

for(i=0;i<f;i++)
{
count[i]=0;
fr[i]=-1;
}
for(i=0;i<n;i++)
{
flag=0;
temp=pg[i];
for(j=0;j<f;j++)
{
if(temp==fr[j])
{
flag=1;
break;
}
}
if((flag==0)&&(k<f))
{
fault++;
fr[k]=temp;
k++;
}
else if((flag==0)&&(k==f))
{
fault++;
for(cnt=0;cnt<f;cnt++)
{
current=fr[cnt];
for(c=i;c<n;c++)
{
if(current!=pg[c])
count[cnt]++;
else
break;
}
}
max=0;
for(m=0;m<f;m++)
{
if(count[m]>max)
{
max=count[m];
p=m;
}
}
fr[p]=temp;
}
printf("\npage %d frame\t",pg[i]);
for(x=0;x<f;x++)
{
printf("%d\t",fr[x]);
}
}
printf("\nTotal number of faults=%d",fault);
return 0;
}

OUTPUT
Ex.No:11.1

DATE : First Fit

First Fit
In the first fit approach is to allocate the first free partition or hole large enough which can accommodate the
process. It finishes after finding the first suitable free partition.
AIM:
To write a program to implement first fit algorithm for memory management.

ALGORITHM:

1. Start the Program


2. Define the function firstFit(int blockSize[], int m, int processSize[], int n)
3. Declare integer variables i, j and allocation[n]
4. Initialize all elements of allocation[] to -1
5. For each process in processSize[], a. For each block in blockSize[], i. If block size is greater than or
equal to process size, 1. Allocate the process to the block 2. Reduce the block size by the process size 3.
Break the loop and move to the next process
6. Print the final allocation of each process with the block number or "Not Allocated"
7. End the function
8. In the main function, a. Declare integer variables m and n b. Initialize blockSize[] and processSize[]
arrays c. Calculate the size of blockSize[] and processSize[] arrays using sizeof operator and divide
them by the size of their first element d. Call the firstFit function with blockSize[], m, processSize[] and
n as arguments
9. Stop the Program

PROGRAM:

#include<stdio.h>
void firstFit(int blockSize[], int m, int processSize[], int n)
{
int i, j;
int allocation[n];
for(i = 0; i < n; i++)
{
allocation[i] = -1;
}

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


{
for (j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
allocation[i] = j;
blockSize[j] -= processSize[i];
break;
}
}
}

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


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

int main()
{
int m;
int n;
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
m = sizeof(blockSize) / sizeof(blockSize[0]);
n = sizeof(processSize) / sizeof(processSize[0]);
firstFit(blockSize, m, processSize, n);
return 0 ;
}
Input and Output:

Input : blockSize[] = {100, 500, 200, 300, 600};


processSize[] = {212, 417, 112, 426};
Output:
Process No. Process Size Block no.
1 212 2
2 417 5
3 112 3
4 426 Not Allocated
OUTPUT:
Process No. Process Size Block no.
1 212 2
2 417 5
3 112 2
4 426 Not Allocated
Ex.No:11.2

DATE : Worst Fit

Worst Fit allocates a process to the partition which is largest sufficient among the freely available partitions
available in the main memory. If a large process comes at a later stage, then memory will not have space to
accommodate it.

AIM:

To write a program to implement Worst fit algorithm for memory management.

ALGORITHM:

1. Create a function named worstFit that takes in parameters:


o blockSize[]: An array of integers representing the sizes of memory blocks.
o m: An integer representing the number of memory blocks.
o processSize[]: An array of integers representing the sizes of processes.
o n: An integer representing the number of processes.
2. Declare an array allocation[] of size n, and initialize all its elements to -1 using memset() function.
3. Loop through all processes from i=0 to i=n-1: a. Initialize wstIdx to -1. b. Loop through all memory
blocks from j=0 to j=m-1: i. If the size of the j-th memory block is greater than or equal to the size of
the i-th process: - If wstIdx is equal to -1, assign j to wstIdx. - Otherwise, if the size of the block
assigned to wstIdx is less than the size of the block assigned to j, assign j to wstIdx. c. If wstIdx is not
equal to -1, then:
o Assign wstIdx to allocation[i].
o Reduce the size of the wstIdx-th block by the size of the i-th process.
4. Print the result of the allocation process: a. Print a header with "Process No.", "Process Size", and
"Block no." as columns. b. Loop through all processes from i=0 to i<n-1: i. Print the process number, its
size, and the block number allocated to it if any, otherwise print "Not Allocated".

PROGRAM:
#include <stdio.h>
#include <string.h>
void worstFit(int blockSize[], int m, int processSize[], int n)
{

int allocation[n];
memset(allocation, -1, sizeof(allocation));
for (int i = 0; i < n; i++)
{
int wstIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (wstIdx == -1)
wstIdx = j;
else if (blockSize[wstIdx] < blockSize[j])
wstIdx = j;
}
}

if (wstIdx != -1)
{
allocation[i] = wstIdx;
blockSize[wstIdx] -= processSize[i];
}
}
printf("\nProcess No.\tProcess Size\tBlock no.\n");
for (int i = 0; i < n; i++)
{
printf(" %d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("%d", allocation[i] + 1);
else
printf("Not Allocated");
printf("\n");
}
}

int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);
worstFit(blockSize, m, processSize, n);
return 0;
}

OUTPUT:
Ex.No:11.3

DATE : Best Fit

Best Fit:

Best fit allocates the process to a partition which is the smallest sufficient partition among the free
available partitions.

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

ALGORITHM:

1. Create a function named 'bestFit' which takes the following parameters:


o an integer array 'blockSize' which represents the size of memory blocks.
o an integer 'm' which represents the total number of memory blocks.
o an integer array 'processSize' which represents the size of processes.
o an integer 'n' which represents the total number of processes.
2. Declare an integer array 'allocation' of size 'n' to store the block id of the block allocated to each
process. Initialize all elements of the array to -1.
3. Loop through each process: a. Find the best fit block for the current process by looping through all
memory blocks. b. If a block is found that can accommodate the current process: i. Assign the block id
to the 'allocation' array for the current process. ii. Reduce the available memory in this block by the size
of the current process.
4. Print the details of each process such as process number, process size, and the block number assigned to
the process.
5. In the main function: a. Initialize two integer arrays 'blockSize' and 'processSize' with the respective
sizes of memory blocks and processes. b. Find the number of memory blocks 'm' and the number of
processes 'n'. c. Call the 'bestFit' function with the above parameters.
6. End of the program.

PROGRAM:

#include<stdio.h>

// Method to allocate memory to blocks as per Best fit algorithm


void bestFit(int blockSize[], int m, int processSize[], int n)
{
// Stores block id of the block allocated to a process
int allocation[n];

// Initially no block is assigned to any process


for (int i = 0; i < n; i++)
allocation[i] = -1;

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i = 0; i < n; i++)
{
// Find the best fit block for current process
int bestIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] > blockSize[j])
bestIdx = j;
}
}

// If we could find a block for current process


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

// Reduce available memory in this block.


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

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


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

// Driver Method
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);
bestFit(blockSize, m, processSize, n);

return 0 ;
}

INPUT & OUTPUT:


Input : blockSize[] = {100, 500, 200, 300, 600};
processSize[] = {212, 417, 112, 426};
Output:
Process No. Process Size Block no.
1 212 4
2 417 2
3 112 3
4 426 5

OUTPUT:

Process No. Process Size Block no.


1 212 4
2 417 2
3 112 3
4 426 5
Ex.No:12

DATE : Implementation of the paging Technique

AIM:
To write a program in C to implement Paging Technique.

ALGORITHM:

1. Include the header file stdio.h.


2. Declare variables to store memory size, page size, the number of pages, the number of processes, the
number of remaining pages, and page table.
3. Prompt the user to enter the memory size and page size.
4. Calculate the number of pages available in memory by dividing memory size by page size.
5. Prompt the user to enter the number of processes.
6. Set the number of remaining pages to the number of pages available in memory.
7. For each process: a. Prompt the user to enter the number of pages required. b. Check if the required
pages are available in the memory. c. If the required pages are not available, print "Memory is Full" and
break the loop. d. Subtract the required pages from the number of remaining pages. e. Prompt the user
to enter the page table for the process. f. Store the page table in a two-dimensional array.
8. Prompt the user to enter the logical address to find the physical address.
9. Prompt the user to enter the process number, page number, and offset.
10. Check if the process number, page number, and offset are valid.
11. If they are valid, calculate the physical address using the page table and offset.
12. Print the physical address.

PROGRAM:

#include<stdio.h>
int main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;
int s[10], fno[10][20];
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);
}
}

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 –
2
3
60
The Physical Address is -- 760

You might also like