Lab Manual

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

EX.NO.

1 BASICS OF UNIX COMMANDS

Objective:

To implement the basic commands in UNIX.

Basic Commands:

Directory Commands

Command Description
pwd Shows the name and location of the directory where you are
curretly working.
ls Gives you a short list of the files in the directory where you
are currently working.
cd Moves you to another directory.
mkdir Creates a new subdirectory inside of the directory where
you are currently working

File related commands


Command Description
CAT>FILE Creates a file
more FILE Display contents of FILE, page by page.

cat FILE Display a file.


cat FILE1 FILE2 > NEW Append FILE1 and FILE2 creating new file NEW.
cat FILE1 >> FILE2 Append FILE1 at the end of FILE2.
sort FILE > NEWFILE Sort FILE, putting sorted version into NEWFILE.
grep ITEM FILE(S) Display lines of FILE(S) which contain ITEM.
wc FILE(S) Count characters, words and lines in FILE(S).
diff FILE1 FILE2 | more Show differences between two versions of a file
cp Type cp followed by the name of an existing file and the name of the new file.

Eg:
cp sourcefile destfile
To copy a file to a different directory specify the directory
instead of filename.

Eg:
cp newfile testdir
To copy a file to a different directory and create a new file name, you need to
specify a directory/a new file name.
Eg:
cp newfile testdir/newerfile
cp newfile ../newerfile
The .. represents one directory up in the hierarchy.

file Type file followed by the name of an existing file in the


directory.
Eg: file emergency3_demo.exe
The chmod command allows you to alter access rights to files and directories. All files and
directories have security permissions that grant the user particular groups‟ or all other users‟
chmod access.
Use chmod followed by the permission you are changing. In very simple form this would be:
chmod 755 filename The example above will grant you full rights, group rights to execute and
read, and all others access to execute the file

Use the table above to define the settings for the three "users." In the command, the first number
refers to your permissions, the second refers to group, and the third refers to general users.
Typing the command: chmod 751 filename
gives you full access, the group read and execute, and all others execute only permission
.
mv Type mv followed by the current name of a file and the new
name of the file.
Eg:
mv oldfile newfile

Type mv followed by the name of a file and the new directory where you'd like to place the file

Eg:
mv newfile testdir
This moves the file named newfile to an existing directory named testdir. Be certain you‟re
specifying a directory name or the mv command alters the name of the file instead of moving it.

Type rm followed by the name of a file to remove the file.


rm Eg:
rm newfile
Use the wildcard character to remove several files at once.

Eg:
rm n* This command removes all files beginning with n.
Type rm -i followed by a filename if you‟d like to be
prompted before the file is actually removed.

Eg:
rm -i newfile
rm -i n*

By using this option, you have a chance to verify the


removal of each file. The -i option is very handy when
removing a number of files using the wildcard character *.
find Search for file with a specific name in a set of files
find -name "rc.conf" -print

This command will search in the current directory and all


sub directories for a file named rc.conf.

Note: The -print option will print out the path of any file
that is found with that name. In general -print will print out
the path of any file that meets the find criteria.

How to search for a string in a selection of files (-exec grep


...).
find. -exec grep "www.athabasca" '{}' \; -print
This command will search in the current directory and all
sub directories. All files that contain the string will have
their path printed to standard output.
Nl filename Inserts line number within the file

General Purpouse commands

date print or set the system date and time to set date and time

date -s "11/20/2003 12:48:00" - Set the date to the date and time shown.

date '+DATE: %m/%d/%y%nTIME:%H:%M:%S' - Would list the time


and date in the below format:

DATE: 02/08/01
TIME:16:44:55
bc Calculator
bc [-c] [-l] [file]
-c Compile only. The output is dc commands that are sent to
the standard output.
-l Define the math functions and initialize scale to 20,
instead of the default zero.
file Name of the file that contains the bc commands to be
calculated this is not a necessary command.

Within the cal.txt file you could have a simple statement such as:
/* Add the value 1+2 /*
1+2
quit

bc cal.txt

When running the above command you will receive the results of the cal.txt
file. Which in this case would be 3.

echo Echo's to the screen what you type after echo. Echo is useful for producing
diagnostics in command files, for sending known data into a pipe, and for
displaying the contents of environment variables.

echo [-n] text

-n On BSD and some variants derived from BSD does not


begin a new line after the echoed text.
text The text that you want to echo to the screen.
echo Hello world
The above example would return "Hello world" to the console
echo * | wc
The above example would list a count of all the files and directories in the
current directory.
cal Calendar for the month and the year.
cal [month] [year]
month Specifies the month for you want the calendar to be
displayed. Must be the numeric representation of the
month. For example: January is 1 and December is 12.
year Specifies the year that you want to be displayed.
Cal - Would give you the calendar for this month.
Cal 12 2000 - Would give you the calendar for December of 2000.
who Displays who is on the system.

man The man command is short for manual


Shows you online manuals on Unix commands.

man [-] [-k keywords] topic


- Displays the manual without stopping.
-k keywords Searches for keywords in all of the manuals available.
topic Displays the manual for the topic or command typed in.
Man mkdir - Lists help information on the mkdir command.
Man -k irc - Quickly searches for manuals containing irc within them.
clear Clears the screen
write Send a message to another user.
write person [ttyname]
person If you wish to talk to someone on your own machine, then
person is just the person's login name. If you wish to talk
to a user on another host, then person is of the form
'user@host'.
If you wish to talk to a user who is logged in more than
once, the ttyname argument may be used to indicate the
appropriate terminal name, where ttyname is of the form
ttyname 'ttyXX' or 'pts/X'

mail One of the ways that allows you to read/send E-Mail


Mail - Opens the mail program with the first message
in the mail (if applicable).
Mail support@computerhope.com - Starts a new e-mail, sending the e- mail to the support at
Computer Hope. When composing a message to terminate the message type a period (.) and
press enter

tty To know terminal name

Filter commands

Grep Finds text within a file.


Eg:
grep "unix" *.htm
search all .htm files in the current directory for any reference of
unix and give results similar to the below example text

Prints all lines of file that contain the pattern, regardless of case.
grep -i pattern file For example, grep -i cg data prints any line of data that contains
"cg," "Cg," "cG," or "CG." The -i option ignores the case of the
string when searching.

grep -v pattern file Prints all lines of the file except those that contain the pattern.

grep -c pattern file Display only the number of matching lines


grep -n pattern file What the "-n" does is tell grep to print out the line number as well
as the line itself.
Search a file for a pattern using full regular expressions.
egrep "support|help|windows" myfile.txt - Would search for
egrep patterns of support help and windows in the file myfile.txt.
sort Sorts the lines in a text file.
sort [-b] [-d] [-f] [-i] [-m] [-M] [-n] [-r] [-u] [+fields] filename [-
o outputfile]
-b Ignores spaces at beginning of the line.
-d Uses dictionary sort order and ignores the
punctuation.
-f Ignores caps
-i Ignores nonprinting control characters.
-m Merges two or more input files into one sorted
output.
-M Treats the first three letters in the line as a month
(such as may.)
-n Sorts by the beginning of the number at the
beginning of the line.

-r Sorts in reverse order


-u If line is duplicated only display once
+fields Sorts by fields , usually by tabs
filename The name of the file that needs to be sorted.
-o outputfile Sends the sorted output to a file.
Sort -r file.txt - Would sort the file, file.txt in reverse order.
uniq Report or filter out repeated lines in a file.
uniq [-c | -d | -u ] [ -f fields ] [ -s char ] [-n] [+m] [input_file [
output_file ] ]
-c Precede each output line with a count of the number
Of times the line occurred in the input.
-d Suppress the writing of lines that are not repeated
In the input.
-u Suppress the writing of lines that are repeated
In the input.
-f fields Ignore the first fields fields on each input line
when doing comparisons, where fields is a positive
Decimal integer.
s char Ignore the first chars characters when doing
comparisons,
-n Equivalent to -f fields with fields set to n.
+m Equivalent to -s chars with chars set to m.
input_file A path name of the input file. If input_file is not
specified, or if the input_file is -, the
standard input will be used.
output_file A path name of the output file. If output_file is not
specified, the standard output will be used.
The results are unspecified if the file named by
output_file is the file named by input_file.
head Displays the first ten lines of a file, unless otherwise stated.
head [-number | -n number] filename
-number The number of the you wants to display.
-n number The number of the you wants to display.
filename The file that you want to display the x amount of
lines of.
Head -15 myfile.txt - Would display the first fifteen lines of
myfile.txt.
tail Delivers the last part of the file.
tail myfile.txt -n 100
The above example would list the last 100 lines in the file
myfile.txt.

cut Cut out selected fields of each line of a file.

Name=`who am i | cut -f1 -d' '` - set name to current login name.
paste Merge corresponding or subsequent lines of files.
The below example would take the input from ls and paste that
input into four columns.
ls | paste - - - -
tr Translate characters.
tr [-c] [-d] [-s] [string1] [string2]
-c Complement the set of characters specified by
string1.
-d Delete all occurrences of input characters that are
specified by string1.
-s Replace instances of repeated characters with a
single character.
string1 First string or character to be changed.
string2 Second string or character to change the string1.
EX:
Echo "12345678 9247" | tr 123456789 computerh - this
example takes an echo response of '12345678 9247' and pipes it
through the tr replacing the appropriate numbers with the letters.
In this example it would return computer hope.

Shell Commands

command Description
Pipe symbol (|). Pipes are a UNIX feature which allows you to connect several
commands together in one line and pass data from one to the next
much like a chain.
pipe connects one commands output to the next commands input
directs UNIX to connect stdout from the first command to the stdin
of the second command
line_count=`wc -l $filename | cut -c1-8`
the wc -l command counts the number of lines in the filename
contained in the variable $filename. This text string is then piped to
the cut command which snips off the first 8 characters and passes
them on to stdout, hence setting the variable line_count.
upper_case=`echo $lower_case | tr '[a-z]' '[A-Z]'`

redirection Redirects work with files, not commands


tr '[a-z]' '[A-Z]' < $in_file > $out_file
The command must come first, the in_file is directed in by the
less_than sign (<) and the out_file is pointed at by the greater_than
sign (>).
tee It is used to store output of a ling pipeline command to be stored for
later use.
$cat mast|sort|tee temp|cut –d “:” –f1

Exercises:

On the spot problems will be given during the lab sessions to make the students to analyze the problem and
find out the suitable method to solve the given problem.
EX.NO.2 PROGRAMS USING THE FOLLOWING SYSTEM CALLS OF UNIX
OPERATING SYSTEM FORK, EXEC, GETPID, EXIT, WAIT, CLOSE, STAT,
OPENDIR, READDIR

Objective:

To implement programs using the following system calls of UNIX fork, exec, getpid, exit, wait, close, stat, opendir,
readdir.

Commands:

fork:

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose
of fork() is to create a new process, which becomes the child process of the caller. After a new child process is
created, both processes will execute the next instruction following the fork() system call. Therefore, we have to
distinguish the parent from the child. This can be done by testing the returned value of fork():

If fork() returns a negative value, the creation of a child process was unsuccessful.

fork() returns a zero to the newly created child process.

fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type
pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid()
to retrieve the process ID assigned to this process.

After the system call to fork(), a simple test can tell which process is the child.

Note: Unix will make an exact copy of the parent's address space and give it to the child. The parent and child
processes have separate address spaces.

exec:

exec is a BOURNE and POSIX shell command that replaces the current shell process with the command specified
after exec. This command does not create a new PID. For example, if you were to run exec <command>, the shell
would be replaced by that command. When that command is exited, the shell will exit.

getpid:

getpid() returns the process ID of the current process

getppid() returns the process ID of the parent of the current process

exit

The exit command terminates a script, just as in a C program. It can also return a value, which is available to the
script's parent process.

wait:

wait, waitpid - wait for process to change state

wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.

waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if
WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned.

waitid(): returns 0 on success or if WNOHANG was specified and no child(ren) specified by id has yet changed
state; on error, -1 is returned.

Each of these calls sets errno to an appropriate value in the case of an error.

close:

close - close a file descriptor


close() returns zero on success. On error, -1 is returned, and errno is set appropriately.

STAT:

stat - display file or file system status or information such as

 File:– Absolute path name of the file.


 Size:– File size in bytes.
 Blocks: – Total number of blocks used by this file.
 IO Block:– IO block size for this file.
 regular file – Indicates the file type. This indicates that this is a regular file. Following are available file
types.
 regular file. ( ex: all normal files ).
 directory. ( ex: directories ).
 socket. ( ex: sockets ).
 symbolic link. ( ex: symbolic links. )
 block special file ( ex: hard disk ).
 character special file. ( ex: terminal device file ).
 Device:– Device number in hex and device number in decimal
 Inode: – Inode number is a unique number for each file which is used for the internal maintenance by the
file system.
 Links:– Number of links to the file
 Access: Access specifier displayed in both octal and character format. Let us see explanation about both the
format.
 Uid:– File owner’s user id and user name are displayed.
 Gid: – File owner’s group id and group name are displayed.
 Access:– Last access time of the file.
 Modify: – Last modification time of the file.
 Change:– Last change time of the inode data of that file.

Opendir:

opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the
directory stream. The stream is positioned at the first entry in the directory
fdopendir() function is like opendir(), but returns a directory stream for the directory referred to by
the open file descriptor fd. After a successful call to fdopendir(), fd is used internally by the implementation, and
should not otherwise be used by the application.
opendir() and fdopendir() functions return a pointer to the directory stream. On error, NULL is returned,
and errno is set appropriately.

readdir:
readdir - read directory entry

int readdir(unsigned int fd, struct dirent *dirp,


unsigned int count);
readdir() reads one dirent structure from the directory pointed at by fd into the memory area pointed to by dirp.
The parameter count is ignored; at most one dirent structure is read. On success, 1 is returned. On end of directory,
0 is returned. On error, -1 is returned, and errno is set appropriately.

Exercises:

On the spot problems will be given during the lab sessions to make the students to analyze the problem and
find out the suitable method to solve the given problem.
EX.NO.3 C PROGRAMS TO SIMULATE UNIX COMMANDS LIKE CP, LS, GREP.

Objective:

To implement the UNIX Commands such as cp, ls, grep in C

Commands:

cp Type cp followed by the name of an existing file and the name of the new file.

Eg:
cp sourcefile destfile
To copy a file to a different directory specify the directory
instead of filename.

Eg:
cp newfile testdir
To copy a file to a different directory and create a new file name, you need to
specify a directory/a new file name.
Eg:
cp newfile testdir/newerfile
cp newfile ../newerfile
The .. represents one directory up in the hierarchy.
ls Gives you a short list of the files in the directory where you
are currently working.
Grep Finds text within a file.
Eg:
grep "unix" *.htm
search all .htm files in the current directory for any reference of
unix and give results similar to the below example text

Prints all lines of file that contain the pattern, regardless of case.
grep -i pattern file For example, grep -i cg data prints any line of data that contains
"cg," "Cg," "cG," or "CG." The -i option ignores the case of the
string when searching.

grep -v pattern file Prints all lines of the file except those that contain the pattern.

grep -c pattern file Display only the number of matching lines


grep -n pattern file
What the "-n" does is tell grep to print out the line number as well
as the line itself.
Search a file for a pattern using full regular expressions.
egrep "support|help|windows" myfile.txt - Would search for
egrep patterns of support help and windows in the file myfile.txt.

Procedure to compile using GCC C/C++ Compiler

 Type cd into the PuTTY terminal, followed by the directory address that holds the C or C++ source code
you wish to compile.
 Type ls if you are using PuTTY to log into a Unix-based machine, or dir if you are using PuTTY to log into
a Windows machine. This lists the files in the current directory. Ensure the source code file you wish to
compile is present.
 Type gcc -o MyExecutable MySourceCode where "MyExecutable" is the name you want your compiled
executable to bear and "MySourceCode" is the name of the source code you want to compile. It will have
the C or CPP file extension, depending on whether it's a C language source file or a C++ language source
file.
Exercises:

On the spot problems will be given during the lab sessions to make the students to analyze the problem and
find out the suitable method to solve the given problem.

EX.NO.4 SHELL PROGRAMMING

Objective:
To implement Shell Programming.

Concepts Involved:
Shell programming is a group of commands grouped together under single filename. The shell interprets
the input, takes appropriate action, and finally displays the output. Shell scripts are dynamically
interpreted, not compiled.

Types of shell:

Bourne shell sh
C shell csh
Korne Shell ksh

Creation and execution of shell scripts using command line editor:

1. creation
$ cat > greet
echo “please enter your name:”
read name
echo “hi! Welcome to this session $name”
Ctrl + D
2. Execution
$ sh greet
please enter your name: jaya
hi! Welcome to this session jaya”

Valid shell variables:

area
a1
account
a_count

Assigning values to variable:


Variable=value

Displaying values of variables:


$ echo value of n is $n

Operators:

Arithmetic Operators provided by the shell are +,- * and /

Logical operators
-a and

-o or
! not

Relational operators
-eq : check fro equality of integers
-ne : check for inequality

-gt : check if one integer is greater than the other


-lt : check if one integer is lesser than the other
-ge : check if one integer is greater than or equal to the other
-le : check if one integer is lesser than or equal to the other.
-f : check if a file is an ordinary file
-d : check if a file is a directory
-r : check if a file is readable
-w : check if a file is write able
-x : check if a file is executable

String comparison operators


= equal to

!= not equal to

Logical operators
-a and

-o or
-! Not

Conditional execution operations

& used to execute a command on successful execution of another command. ||


used to execute another command on failure of another command.

Read command
Used to read the value of the shell variable from a user.

Comment statement
# this is a text program.

Programming language construct

1.a)if..then…else…fi b) if..then..elif..else ..fi


2.for…do…done

3.while..do..done

4.until…do..done

5.case …esac

1) if construct

useful for executing a set of commands based on the condition being true and alternate set of
commands to be executed if the condition is false. Ex. if (grep India countri.dat)

then
echo “pattern found”
else
echo “pattern not found”
fi

2) for construct

used to perform same set of operations on a list of values.


for variable in value1 value2 value3 …
do

Commands
done

Ex. for k in 1 2 3 4 5
do
echo “the number is $k”

echo “the square of the number is `expr $k \* $k` “


done

3)while construct

Repeatedly executing group of commands as long as the condition is true.


while condition
do

Commandlist

done

Ex.to print 3 numbers


a=1
while [$a -le 3]
do
echo $a
$a=`expr $a+1`
done
o/p. 1 2 3
4) until construct

Repeatedly executing group of commands until a condition is true.


until condition
do
Commandlist
done

Ex. to print 3 numbers


a=1
until [$a -le 3]
do
echo $a
$a=`expr $a+1`

done

o/p. 1 2 3
5) case construct:
case value in
choice1) commands;;
choice2)commands;;
….
esac
Ex. $echo “enter a value”
read myval
case “$myval” in

1) echo zero;;
2) echo one;;
3) echo two;;
4) echo three;;
*) echo “invalid argument”;;
esac
Exercises:

On the spot problems will be given during the lab sessions to make the students to analyze the problem and
find out the suitable method to solve the given problem

EX.NO.5 C PROGRAMS TO IMPLEMENT THE VARIOUS CPU SCHEDULING


ALGORITHMS

Objective:

To implement the following CPU scheduling algorithm using C


a)First Come First Serve, b) Shortest Job First c)Round Robin Scheduling,d) Priority Scheduling

FIRST COME FIRST SERVE

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 arrives first is given the CPU after finishing its request only it will allow CPU
to execute other process.

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

SHORTEST JOB FIRST

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.

ROUND ROBIN :

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:

Step 1: Initialize all the structure elements


Step 2: Receive inputs from the user to fill process id,burst time and arrival time.
Step 3: Calculate the waiting time for all the process id.
i) The waiting time for first instance of a process is calculated as:
a[i].waittime=count + a[i].arrivt
ii) The waiting time for the rest of the instances of the process is
calculated as:
a) If the time quantum is greater than the remaining burst time then
waiting time is calculated as:
a[i].waittime=count + tq
b) Else if the time quantum is greater than the remaining burst
time then waiting time is calculated as:
a[i].waittime=count - remaining burst time
Step 4: Calculate the average waiting time and average turnaround time
Step 5: Print the results of the step 4

PRIORITY SCHEDULING

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 Priority Scheduling algorithm. In this
algorithm the process which has highest priority executed first. After finishing its request only it will allow CPU to
execute next process which has next priority level.

ALGORITHM:

Step1: Get the number of process, burst time and priority.


Step2: Using for loop i=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 turnaround time is calculated by adding all total time of each process.
Step7: Calculate Average waiting time by dividing the total waiting time by total number of process.
Step8: Calculate Average turnaround time by dividing the total time by the number of process.
Step9: Display the result.

Exercises:

On the spot problems will be given during the lab sessions to make the students to analyze the problem and
find out the suitable method to solve the given problem

EX.NO.6 SEMAPHORES

Objective:

To implement the concepts of Semaphores in producer consumer problem.

Concepts Involved:

Definition: Semaphore

A semaphore is a shared variable/integer variable to synchronize the progress of interacting processes. It is


basically a synchronizing tool and is accessed only through two standard atomic operations, wait and
signal. Atomic operations means executing operation without interruption. 

Principle

• Two or more processes can cooperate by means of simple signals, such that processes is forced to stop at a
specified place unit it has received a specific signal, For signaling special variables used called semaphore. 
• To transmit a signal by semaphores, a process is to execute the primitive signal(s). To receive a signal by
semaphores, a process executes the primitives wait(s). 
• If the corresponding signal has not yet been transmitted; the process is suspended until the transmission takes
place.

Operations of Semaphore:

1. A semaphore may be initialized to a non-negative value. 


2. The ‘wait’ operation decrements the semaphore value by one. If the value becomes negative, then the process
executing the wait is blocked. 
3. The ‘signal’ operation increments the semaphore value. If the value is not positive, then a process blocked by a
wait operation is unblocked. 

Disadvantages: 
• We must keep the value of S=1 
• Busy waiting which consumes many CPU cycles.

Wait : decrement the value of its argument S as soon as it would become non-negative.

Pseudocode

wait(S) {
while (S <= 0)
// no-op( No Operation)
s--;
}
Signal : increment the value of its argument, S as an individual operation.
Singnal(s){
S++;}
Note:

• Modifications to the integer value of the semaphore in the wait and signal operations must be executed indivisibly.
That is, when one process modifies the semaphore value, no other process can simultaneously modify that same
semaphore value. 
• A semaphore is a programming concept that is frequently used to solve multi-threading problems.

Producer–Consumer problem

Producer–Consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process
synchronization problem. The problem describes two processes, the producer and the consumer, who share a
common, fixed-size buffer used as a queue.

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


EX.NO.7 SHARED MEMORY AND IPC

Objective:

To implement the concepts of IPC using shared memory

Inter process communication (IPC)

Inter process communication (IPC) is a mechanism which allows processes to communicate each other and
synchronize their actions. The communication between these processes can be seen as a method of co-operation
between them. Processes can communicate with each other using these two ways:
 Shared Memory
 Message passing

Shared Memory Message Passing

Shared Memory:
Algorithm:
Server:
1. Define shared memory size of 30 bytes
2. Define the key to be 5600
3. Create a shared memory using shmget () system calls and gets the shared memory id in variable shmid.
4. Attach the shared memory to server data space
5. Get the content to be placed in the shared memory from the user of the server.
6. Write the content in the shared memory, which will read out by the client.
7. stop

Client :
1. Define the key to be 5600
2. Attach the client to the shared memory created by the server.
3. Read the content from the shared memory.
4. Display the content on the screen.
5. stop

EX.NO.8 BANKERS ALGORITHM FOR DEADLOCK AVOIDANCE

Objective:

To detect and prevent deadlock using Banker‟s algorithm.

Concepts Involved:

Deadlock Characteristics
.
 Mutual Exclusion.
 Hold and Wait.
 No preemption.
 Circular wait.
Deadlock Avoidance: Deadlock can be avoided by eliminating any of the above four condition

Banker’s Algorithm

Bankers’s Algorithm is resource allocation and deadlock avoidance algorithm which test all the request made by
processes for resources, it check for safe state, if after granting request system remains in the safe state it allows the
request and if there is no safe state it don’t allow the request made by the process.
Inputs to Banker’s Algorithm
1. Max need of resources by each process.
2. Currently allocated resources by each process.
3. Max free available resources in the system.
Request will only be granted under below condition.
1. If request made by process is less than equal to max need to that process.
2. If request made by process is less than equal to freely availbale resource in the system.
Example
Total resources in system:
ABCD
6576
Available system resources are:
ABCD
3112
Processes (currently allocated resources):
ABCD
P1 1 2 2 1
P2 1 0 3 3
P3 1 2 1 0
Processes (maximum resources):
ABCD
P1 3 3 2 2
P2 1 2 3 4
P3 1 3 5 0

Need = maximum resources - currently allocated resources.

Processes (need resources):

ABCD

P1 2 1 0 1

P2 0 2 0 1

P3 0 1 4 0

Algorithm:

Safety algorithm

1. Start
2. Initialize a temporary vector W (Work) to equal the available vector A.
3. Find an index i (row i) such that
Need i < = W
If no such row exists, the system will deadlock, since no process can run to completion.

4. If such a row is found, mark this process as finished, and add all its resources to W
Vector i,
W = W + Ci
Go to step 2, until either all processes are marked terminated (in this case initial state is safe), or until a
deadlock occurs, in which the state is not safe.

Resource – request algorithm

1. If Request i < = Need i , go to step 2. Otherwise, error


2. If Request i < = Available, go to step 3. Otherwise, Pi must wait, since resources are not available
3. Modify the state ( the system pretend to have allocated the requested resources to process Pi ) Available =
Available – Request i
Allocation i = Allocation i + Request i
Need i = Need i – Request i
4. If the resulting state is safe, the transaction is completed and process Pi is allocated its resources. If new
state is unsafe, then Pi must wait for Request i and the old state is restored.
5. Stop.
EX.NO.9 DEADLOCK DETECTION ALGORITHM

Objective:

To implement the procedure to detect whether deadlock will occur or not.

Concepts Involved:

Procedure I: Simply detects the existence of a Cycle:

1. Start at any vertex finds all its immediate neighbors.


2. From each of these find all immediate neighbors, etc.
3. Until a vertex repeats (there is a cycle) or one cannot continue (there is no cycle).
4. Stop.
Procedure II: On a copy of the graph:

1. See if any Processes NEEDs can all be satisfied.


2. If so satisfy the needs with holds and remove that Process and all the Resources it holds from
3. the graph.
4. If any Process are left Repeat step a
5. If all Processes are finally removed by this procedure there is no Deadlock in the original graph, if not
there is.
6. Stop.

Sample Output

Enter the no. Of processes 3

Enter the no of resources instances 3


Enter the max matrix
368
433
344

Enter the allocation matrix


333
203
124
Enter the available resources
120
Process allocation max available
P1 3 3 3 3 6 8 1 2 0
P2 2 0 3 4 3 3
P3 1 2 4 3 4 4
System is in deadlock and deadlock process are
P0 p1 p2

EX.NO.10 C PROGRAM TO IMPLEMENT THREADING & SYNCHRONIZATION


APPLICATIONS

Objective:

To implement Thread and synchronization using C in Banking application.

Procedure:

1. Create a Bank Database


2. Create functions for adding a new user, depositing the amt, withdrawing the amt & viewing the
customer
3. Create a thread for each functionality
4. Implement the concurrency control among the threads
5. Function add new user
a. Get the user details namely, Acno, Name & Bank Balance

b. Write the user details to the bank database


6. Function Deposit

a. Get the Acno & Amt

b. Update the Bank balance for the given Acno


7. Function Withdraw
a. Get the Acno & Amt

b. Update the Bank balance for the given Acno


8. Function View

a. Get the Acno


b. Display the account details
EX.NO.11 MEMORY ALLOCATION METHODS FOR FIXED PARTITION A)
FIRST FIT B) WORST FIT C) BEST FIT

Objective:

To implement the concepts of memory allocation methods for fixed partition.

Concepts Involved:
First Fit
The partition is allocated which is first sufficient from the top of Main Memory.
Implementation:
1- Input memory blocks with size and processes with size.
2- Initialize all memory blocks as free.
3- Start by picking each process and check if it can
be assigned to current block.
4- If size-of-process <= size-of-block if yes then
assign and check for next process.
5- If not then keep checking the further blocks.
Example:
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 2
4 426 Not Allocated
Best fit
It allocates the process to a partition which is the smallest sufficient partition among the free available partitions
Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
minimum block size that can be assigned to
current process i.e., find min(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
it to the current process.
5- If not then leave that process and keep checking
the further processes.
Example:
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

Worst Fit
It 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.
Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
maximum block size that can be assigned to
current process i.e., find max(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
it to the current process.
5- If not then leave that process and keep checking
the further processes.
Example:
Input : blockSize[] = {100, 500, 200, 300, 600};
processSize[] = {212, 417, 112, 426};
Output:
Process No. Process Size Block no.
1 212 5
2 417 2
3 112 5
4 426 Not Allocated
EX.NO.12 PAGING TECHNIQUE OF MEMORY MANAGEMENT

Objective:

To implement the concepts of paging.

Concepts Involved:

Paging

It is a memory management scheme that eliminates the need for contiguous allocation of physical memory. This
scheme permits the physical address space of a process to be non – contiguous.

The mapping from virtual to physical address is done by the memory management unit (MMU) which is a hardware
device and this mapping is known as paging technique.
 The Physical Address Space is conceptually divided into a number of fixed-size blocks, called frames.
 The Logical address Space is also spitted into fixed-size blocks, called pages.
 Page Size = Frame Size

Example:
 Physical Address = 12 bits, then Physical Address Space = 4 K words
 Logical Address = 13 bits, then Logical Address Space = 8 K words
 Page size = frame size = 1 K words (assumption)

Implementation:

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

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.
EX.NO.13 PAGE REPLACEMENT ALGORITHMS A) FIFO B) LRU C) LFU

Objective:

To implement the concepts of page replacement algorithms such as FIFO,LRU,LFU

Concepts Involved:

Page Replacement Algorithm

These Algorithms are needed to decide which page needed to be replaced when new page comes in. Whenever a
new page is referred and not present in memory, page fault occurs and Operating System replaces one of the
existing pages with newly needed page

First In First Out (FIFO)

This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the
memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of
the queue is selected for removal.

FIFO Implementation

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. Forma 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

Least Recently Used (LRU)–In this algorithm page will be replaced which is least recently used.

LRU Implementation

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

Least Frequently Used (LFU)

In LFU we check the old page as well as the frequency of that page and if the frequency of the page is larger than
the old page we cannot remove it and if all the old pages are having same frequency then take last i.e FIFO method
for that and remove that page.

LFU Implementation

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 frequently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process
EX.NO.14 FILE ORGANIZATION TECHNIQUES

Objective:

To implement the concepts of file organization technique

Concepts Involved:

a) Single level directory

Algorithm:

1. Start
2. Declare the number, names and size of the directories and file names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories.
5. Stop.
Output:
enter number of directorios:2
enter names of directories: abc xyz
enter size of directories:3 4
enter the file names :a b c x y z l
directory size filenames
*********************************
abc 3 a
b
c
xyz 4 x
y
z
l

b) Two level directory

Algorithm:

1. Start
2. Declare the number, names and size of the directories and subdirectories and file names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories and subdirectories.
5. Stop.
Output:

enter number of directories:2


enter directory 1 names:xyz
enter size of directories:3
enter subdirectory name and size:x
2
enter file name:tim
enter file name:tulip
enter subdirectory name and size:y
1

enter file name:user


enter subdirectory name and size:z
1
enter file name:yash
enter directory 2 names:abc
enter size of directories:2
enter subdirectory name and size:a
1
enter file name:wee
enter subdirectory name and size:b
4
enter file name:seed
enter file name:saad
enter file name:gyd
enter file name:kim
dirname size subdirname size files
******************************************************
xyz 3 x 2 tim tulip
y 1 user
z 1 yash
abc 2 a 1 wee
b 4 seed saad gyd kim
Press any key to continue . . .
c. Hierarchical directory Structure

Algorithm:

1. Start
2. Declare the number, names and size of the directories and subdirectories and file names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories and subdirectories.
5. Stop.

d. Directed Acyclic Graph (DAG)

Algorithm:

1. Start
2. Collect set of nodes 1, 2, …, n
3. Get the value of an edge (i,j) whenever i < j
4. Calculate N-choose-2 = n (n-1)/2 edges, but no cycles.
5. Stop.
EX.NO.15 FILE ALLOCATION STRATEGIES A) SEQUENTIAL B) INDEXED C) LINKED

Objective:

To implement the concepts of file allocation strategies

Concepts Involved:

a. Sequential file allocation strategy


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

Output:
Enter no. of Files ::2
Enter file 1 name ::x.c
Enter file1 size(in kb)::4
Enter Starting block of 1::100
Enter blocksize of File1(in bytes)::512
Enter file 2 name ::y.c
Enter file2 size(in kb)::2
Enter Starting block of 2::500
Enter blocksize of File2(in bytes)::256
Enter the Filename ::y.c
Fname   Start   Nblocks Blocks
---------------------------------------------
y.c     500     8       500->501->502->503->504->505->506->507->
---------------------------------------------
Do U want to continue ::(Y:n) n            

b. Indexed file allocation strategy


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

Output:
Enter no. of Files :2
Enter file 1 name ::x.c
Enter file1 size(in kb)::1
Enter blocksize of File1(in bytes)::512
Enter file 2 name ::y.c
Enter file2 size(in kb)::1
Enter blocksize of File2(in bytes)::512
Enter blocks for file1
Enter the 1block ::1000
Enter the 2block ::1001
Enter blocks for file2
Enter the 1block ::2000
Enter the 2block ::2001
Enter the Filename ::x.c
Fname   Fsize   Bsize   Nblocks Blocks
---------------------------------------------
x.c     1       512     2       1000->1001->
---------------------------------------------

Do U want to continue ::(Y:n)1


Enter the Filename ::y.c
Fname   Fsize   Bsize   Nblocks Blocks
---------------------------------------------
y.c     1       512     2       2000->2001->
---------------------------------------------
Do U want to continue ::(Y:n)0

c. Linked file allocation strategy


Algorithm:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom of the stack
Step 6: Stop the allocation.
Output:
Enter file1 size(in kb)::1
Enter blocksize of File1(in bytes)::512
Enter file 2 name ::sudee
Enter file2 size(in kb)::1
Enter blocksize of File2(in bytes)::1024
Enter Starting block of file::1100
Enter Ending block of file::1600
Enter blocks for file1::
Enter the 1block ::102
Enter the 2block ::104
Enter Starting block of file::2200
Enter Ending block of file::2500
Enter blocks for file2::
Enter the 1block ::201
Enter the Filename ::xxx
Fname   Fsize   Bsize   Nblocks Blocks
---------------------------------------------
xxx    1       512     2       100->102->104->600->
---------------------------------------------

Do U want to continue ::(Y:n)1

Enter the Filename ::yyy

Fname   Fsize   Bsize   Nblocks Blocks


---------------------------------------------
yyy   1       1024    1       200->201->500->
---------------------------------------------
Do U want to continue ::(Y:n)0

You might also like