CS8461 - Operating System Laboratory Manual prepared for the Engineering graduates admitted under 2017 Regulations, Anna University affiliated institutions of TamilNadu,India
1. R 2 0 1 7 ( C B C S ) - A F F I L I A T E D I N S T I T U T I O N S
Anna University, Chennai
CS8461-Operating
SystemsLabManual
2. O P E R A T I N G S Y S T E M S
Practical Guide
S.Selvi, Assistant Professor
Department of Computer Science and Engineering
Government College of Engineering
Bargur, Krishnagiri, Tamilnadu
635104
3. i
Table of Contents
CHAPTER
No.
TITLE PAGE
No.
A
B
C
D
D.1
How to use this manual
Syllabus
Mapping of Course Outcomes with Programme Outcomes
LIST OF PROCEDURES
BASICS OF UNIX COMMANDS
3
4
5-8
9-61
9-11
1.1 Study of UNIX OS 9
BASICS OF SHELL COMMANDS 12-21
1.2 Study of basic shell commands 12
D.2 SHELL PROGRAMMING 22-31
2.1 Implementation of shell program to find area and circumference of circle 22
2.2 Implementation of shell program to find simple interest 23
2.3 Implementation of shell program to find greatest of three numbers 24
2.4 Implementation of shell program to check a year as leap or not 25
2.5 Implementation of shell program to display student grade 26
2.6 Implementation of shell program to find factorial of a given number 27
2.7 Implementation of shell program to generate fibonacci series 28
2.8 Implementation of shell program to check a number as prime or not 29
2.9 Implementation of shell program to check a number as palindrome or not 30
2.10 Implementation of shell program to check a number as armstrong or not 31
D.3 SYSTEM CALLS & I/O SYSTEM CALLS 32-36
3.1 Implementation of C programs using the following system calls of UNIX
operating system fork (), getpid (), getppid (), wait (), exit (), opendir(),
readdir(), closedir()
32
3.2 Implementation of C programs using the following I/O system calls of
UNIX operating system open (), close (), read (), write()
35
D.4 SIMULATION OF UNIX COMMAND 37
4 Implementation of C program to simulate UNIX command – LS 37
D.5 CPU SCHEDULING ALGORITHMS 38-43
5.1 Implementation of first come first serve scheduling Algorithm 38
5.2 Implementation of shortest job first scheduling Algorithm 39
5.3 Implementation of priority scheduling Algorithm 41
5.4 Implementation of round robin scheduling Algorithm 43
D.6 PROCESS SYNCHRONISATION 44
6 Implementation of semaphores concept 44
D.7 SHARED MEMORY AND INTERPROCESS COMMUNICATION 45
4. ii
7 Implementation of shared memory and interprocess communication concept 45
D.8 DEADLOCK DETECTION ALGORITHM 46
8 Implementation of banker‟s Algorithm for deadlock detection 46
D.9 DEADLOCK AVOIDANCE ALGORITHM 47
9 Implementation of banker‟s Algorithm for deadlock avoidance 47
D.10 THREADING 48
10 Implementation of multithreading concept 48
D.11 MEMORY ALLOCATION METHODS FOR FIXED PARTITION 49-50
11 Implementation of first fit, best fit and worst fit memory allocation methods
for fixed partition
49
D.12 PAGING TECHINIQUE 51
12 Implementation of paging technique of memory management 51
D.13 PAGE REPLACEMENT ALGORITHMS 52-54
13.1 Implementation of FIFO page replacement algorithm 52
13.2 Implementation of LRU page replacement algorithm 53
13.3 Implementation of LFU page replacement algorithm 54
D.14 FILE ORGANIZATION TECHNIQUES 55-58
14.1 Implementation of single level directory structure for file organization 55
14.2 Implementation of two level directory structure for file organization 56
14.3 Implementation of hierarchical level directory structure for file organization 57
14.4 Implementation of directed acyclic graph directory structure for file
organization
58
D.15 FILE ALLOCATION STRATEGIES 59-61
15.1 Implementation of sequential file allocation strategy 59
15.2 Implementation of indexed file allocation strategy 60
15.3
E
Implementation of linked file allocation strategy
Appendix
Source Code
61
63-132
63
5. 3
How to Use This Manual
This manual is designed to cater the needs of B.E.CSE Second Year students for understanding the
laboratory experiments that will be conducted during their academic year. This is prepared on the basis of
guidelines prescribed by Anna University 2017 - syllabi for their affiliated institutions. The students can
understand the programs that would be conducted in the laboratory easier and this serves more or less like a
reference book to the students and the faculty of this course.
I, sincerely thank the Almighty,
My parents Thiru S.Sivaperumal, Tmt.Kalyani Sivaperumal , my spouse Mr.N.Rajan and my son
Mr.R.Vignesh Aditya
My dearest friend Mrs.Sujatha Paramasivam and Mr. Paramasivam and Mr. Harish Arasu,
My student, Mr. R. Balaji
in completing this lab manual successfully.
Chapter
A
6. 4
Syllabus
Lecture: 0Hrs. Tutorial: 0Hrs. Practical: 4Hrs. Credits: 2
OBJECTIVES
To learn Unix commands and shell programming
To implement various CPU Scheduling Algorithms
To implement Process Creation and Inter Process Communication.
To implement Deadlock Avoidance and Deadlock Detection Algorithms
To implement Page Replacement Algorithms
To implement File Organization and File Allocation Strategies
LIST OF EXPERIMENTS
1. Basics of UNIX commands
2. Write programs using the following system calls of UNIX operating system fork, exec, getpid, exit,
wait, close, stat, opendir, readdir
3. Write C programs to simulate UNIX commands like cp, ls, grep, etc.
4. Shell Programming
5. Write C programs to implement the various CPU Scheduling Algorithms
6. Implementation of Semaphores
7. Implementation of Shared memory and IPC
8. Bankers Algorithm for Deadlock Avoidance
9. Implementation of Deadlock Detection Algorithm
10. Write C program to implement Threading & Synchronization Applications
11. Implementation of the following Memory Allocation Methods for fixed partition
a) First Fit b) Worst Fit c) Best Fit
12. Implementation of Paging Technique of Memory Management
13. Implementation of the following Page Replacement Algorithms
a) FIFO b) LRU c) LFU
14. Implementation of the various File Organization Techniques
15. Implementation of the following File Allocation Strategies
a) Sequential b) Indexed c) Linked
TOTAL: 60 PERIODS
OUTCOMES:
At the end of the course, the student should be able to
1. Compare the performance of various CPU Scheduling Algorithms
2. Implement Deadlock avoidance and Detection Algorithms
3. Implement Semaphores
4. Create processes and implement IPC
5. Analyze the performance of the various Page Replacement Algorithms
6. Implement File Organization and File Allocation Strategies
Chapter
B
7. 5
Mapping of Course Outcomes with
Programme Outcomes
ANNA UNIVERSITY, CHENNAI
(AFFILIATED INSTITUTIONS B.E. COMPUTER SCIENCE AND ENGINEERING)
REGULATIONS – 2017 CHOICE BASED CREDIT SYSTEM
PROGRAM EDUCATIONAL OBJECTIVES (PEOs):
1. To enable graduates to pursue higher education and research, or have a successful career in
industries associated with Computer Science and Engineering, or as entrepreneurs.
2. To ensure that graduates will have the ability and attitude to adapt to emerging technological
changes.
PROGRAM SPECIFIC OBJECTIVES (PSOs)
1. To analyze, design and develop computing solutions by applying foundational concepts of
Computer Science and Engineering.
2. To apply software engineering principles and practices for developing quality software for scientific
and business applications.
3. To adapt to emerging Information and Communication Technologies (ICT) to innovate ideas and
solutions to existing/novel problems.
PROGRAM OUTCOMES POs:
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals
and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
Chapter
C
8. 6
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one„s own work, as a member and leader in
a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Mapping of course outcomes with programme outcomes is listed in Table 1.
Table 1
S.No. Experiments Course
Outcomes
Programme
Outcomes
D.1
1.1
1.2
BASICS OF UNIX COMMANDS
Study of UNIX OS
BASICS OF SHELL COMMANDS
Study of basic shell commands
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.2
2.1
2.2
2.3
SHELL PROGRAMMING
Implementation of shell programg to find area and
circumference of circle
Implementation of shell program to find simple
interest
Implementation of shell program to find greatest
of three numbers
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
9. 7
S.No. Experiments Course
Outcomes
Programme
Outcomes
2.4
2.5
2.6
2.7
2.8
2.9
2.10
Implementation of shell program to check a year
as leap or not
Implementation of shell program to display
student grade
Implementation of shell program to find factorial
of a given number
Implementation of shell program to generate
fibonacci series
Implementation of shell program to check a
number as prime or not
Implementation of shell program to check a
number as palindrome or not
Implementation of shell program to check a
number as armstrong or not
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.3
3.1
3.2
SYSTEM CALLS & I/O SYSTEM CALLS
Implementation of C programs using the
following system calls fork(), getpid(), getppid(),
wait(), exec(), exit(), opendir(), readdir(), closedir()
Implementation of C programs using the I/O
system calls open(), close(), read(), write()
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.4
4
SIMULATION OF UNIX COMMAND
Implementation of C program to simulate UNIX
command – LS
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.5
5.1
5.2
5.3
5.4
CPU SCHEDULING ALGORITHMS
Implementation of first come first serve
scheduling Algorithm
Implementation of shortest job first scheduling
Algorithm
Implementation of priority scheduling Algorithm
Implementation of round robin scheduling
Algorithm
CO1 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.6
6
PROCESS SYNCHRONISATION
Implementation of semaphores concept
CO1 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.7
7
SHARED MEMORY AND
INTERPROCESS COMMUNICATION
Implementation of shared memory and
interprocess communication concept
CO1 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.8
8
DEADLOCK DETECTION ALGORITHM
Implementation of banker‟s Algorithm for
deadlock detection
CO1 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.9
9
DEADLOCK AVOIDANCE ALGORITHM
Implementation of banker‟s Algorithm for
deadlock avoidance
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
10. 8
S.No. Experiments Course
Outcomes
Programme
Outcomes
D.10
10
THREADING
Implementation of multithreading concept
CO4 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.11
11
MEMORY ALLOCATION METHODS FOR
FIXED PARTITION
Implementation of first fit, best fit and worst fit
memory allocation methods for fixed partition
CO3 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.12
12
PAGING TECHNIQUE
Implementation of paging technique of memory
management
D.13
13.1
13.2
13.3
PAGE REPLACEMENT ALGORITHMS
Implementation of FIFO page replacement
Algorithm
Implementation of LRU page replacement
Algorithm
Implementation of LFU page replacement
Algorithm
CO2 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.14
14.1
14.2
14.3
14.4
FILE ORGANIZATION TECHNIQUES
Implementation of single level directory file
organization technique
Implementation of two level directory file
organization technique
Implementation of hierarchical level directory file
organization technique
Implementation of directed acyclic graph
directory file organization technique
CO6 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
D.15
15.1
15.2
FILE ALLOCATION STRATEGIES
Implementation of sequential file allocation
strategy
Implementation of indexed file allocation strategy
CO2 PO1,PO2,PO3,PO8,
PO9,PO10,PO12
11. 9
LISTOFPROCEDURES
D.1 BASICS OF UNIX COMMANDS
1.1 StudyofUNIXOS
Unix (officially trademarked as UNIX, sometimes also written as UNIX with small caps) is a
computer operating system originally developed in 1969 by a group of AT&T employees at Bell
Labs, including Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna. Today's Unix
systems are split into various branches, developed over time by AT&T as well as various commercial
vendors and non-profit organizations.
Unix was designed to be portable, multi-tasking and multi-user in a time-sharing
configuration. Unix systems are characterized by various concepts: the use of plain text for storing
data; a hierarchical file system; treating devices and certain types of inter-process communication
(IPC) as files; and the use of a large number of software tools, small programs that can be strung
together through a command line interpreter using pipes, as opposed to using a single monolithic
program that includes all of the same functionality. These concepts are known as the Unix
philosophy.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows
which provides an easy to use environment. However, knowledge of UNIX is required for
operations which aren't covered by a graphical program, or for when there is no windows interface
available, for example, in a telnet session.
Types of UNIX
There are many different versions of UNIX, although they share common similarities. The
most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X.
The UNIX operating system is made up of three parts; the kernel, the shell and the programs.
The Kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user types
rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the
file containing the program rm, and then requests the kernel, through system calls, to execute the
program rm on myfile. When the process rm myfile has finished running, the shell then returns the
UNIX prompt $ to the user, indicating that it is waiting for further commands.
The Shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login
program checks the username and password, and then starts another program called the shell. The
shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges
Chapter
D
12. 10
for them to be carried out. The commands are themselves programs: when they terminate, the shell
gives the user another prompt ($ on our systems).
The adept user can customize his/her own shell, and users can use different shells on the
same machine.
Popular Unix shells include:
Bourne shell (sh)
o Almquist shell (ash)
Debian Almquist shell (dash)
o Bourne-Again shell (bash)
o Korn shell (ksh)
C shell (csh)
o TENEX C shell (tcsh)
Es shell (es)
esh (Unix) – Easy Shell
friendly interactive shell (fish)
rc shell (rc) – shell for Plan 9 and Unix
runscript – The initial shell interpreter used to process startup scripts in Gentoo
scsh (Scheme Shell)
Stand-alone Shell (sash)
Z shell
Files and Processes
Everything in UNIX is either a file or a process. A process is an executing program identified
by a unique PID (process identifier). A file is a collection of data. They are created by users using text
editors, running compilers etc.
Examples of files:
A document (report, essay etc.)
The text of a program written in some high-level programming language
Instructions comprehensible directly to the machine and incomprehensible to a casual user,
for example, a collection of binary digits (an executable or binary file);
A directory, containing information about its contents, which may be a mixture of other
directories (subdirectories) and ordinary files.
The Directory Structure
All the files are grouped together in the directory structure. The file-system is arranged in a
hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root
(written as a slash / )
13. 11
In the diagram above, we see that the home directory of the undergraduate student "ee51vn"
contains two sub-directories (docs and pics) and a file called report.doc.
The full path to the file report.doc is "/home/its/ug1/ee51vn/report.doc"
14. 12
D.2 BASICS OF SHELL COMMANDS
2.2 Study of basic shell commands
1. Listing Files and Directories
ls (list)
When you first login, your current working directory is your home directory. Your home
directory has the same name as your user-name, for example, cs1ab, and it is where your personal
files and subdirectories are saved.
To find out what is your home directory, type
$ ls
The ls command lists the contents of your current working directory.
ls does not, in fact, cause all the files in your home directory to be listed, but only those ones whose
name does not begin with a dot (.) Files beginning with a dot (.) are known as hidden files and usually
contain important program configuration information. They are hidden because you should not
change them unless you are very familiar with UNIX!!!
To list all files in your home directory including those whose names begin with a dot, type
$ ls -a
As you can see, ls -a lists files that are normally hidden.
2. Making Directories
mkdir (make directory)
We will now make a subdirectory in your home directory to hold the files. To make a
subdirectory called student in your current working directory type
$ mkdir student
To see the directory you have just created, type
$ ls
3. Changing to a Different Directory
cd (change directory)
The command cd directory means change the current working directory to 'directory'. The
current working directory may be thought of as the directory you are in, i.e. your current position in
the file-system tree.
To change to the directory you have just made, type
$ cd student
Type ls to see the contents (which should be empty)
4. The Directories . and ..
Still in the student directory, type
% ls -a
As you can see, in the student directory (and in all other directories), there are two special directories
called (.) and (..)
The current directory (.)
In UNIX, (.) means the current directory, so typing
% cd .
NOTE: there is a space between cd and the dot means stay where you are (the student directory).
This may not seem very useful at first, but using (.) as the name of the current directory will save a lot
of typing, as we shall see later.
The parent directory (..)
15. 13
(..) means the parent of the current directory, so typing
% cd ..
will take you one directory up the hierarchy (back to your home directory).
Note: typing cd with no argument always returns you to your home directory. This is very useful if
you are lost in the file system.
5. Pathnames
pwd (print working directory)
Pathnames enable you to work out where you are in relation to the whole file-system. For
example, to find out the absolute pathname of your home-directory, type cd to get back to your
home-directory and then type
% pwd
The full pathname will look something like this -
/home/its/ug1/ee51vn
Which means that ee51vn (your home directory) is in the sub-directory ug1 (the group directory),
which in turn is located in the it’s sub-directory, which is in the home sub-directory, which is in the
top-level root directory called “/ “.
6. Copying Files
cp (copy)
cp file1 file2 is the command which makes a copy of file1 in the current working directory
and calls it file2.
7. Moving files
mv (move)
mv file1 file2 moves (or renames) file1 to file2
To move a file from one place to another, use the mv command. This has the effect of
moving rather than copying the file, so you end up with only one file rather than two.
It can also be used to rename a file, by moving the file to the same directory, but giving it a
different name. First, change directories to your student directory. Then, inside the student
directory, type
16. 14
$ mv science.txt student/.
Type ls and ls backups to see if it has worked.
8. Removing Files and Directories
rm (remove), rmdir (remove directory)
To delete (remove) a file, use the rm command. As an example, we are going to create a copy
of the science.txt file then delete it.
Inside your student directory, type
$ cp science.txt tempfile.txt
$ ls
$ rm tempfile.txt
$ ls
You can use the rmdir command to remove a directory (make sure it is empty first). Try to
remove the backups directory. You will not be able to since UNIX will not let you remove a non-
empty directory.
9. Displaying the Contents of a File on the Screen
clear (clear screen)
You may like to clear the terminal window of the previous commands so the output of the
following commands can be clearly understood.
At the prompt, type
$ clear
This will clear all text and leave you with the $ prompt at the top of the window.
cat (concatenate)
The command cat can be used to display the contents of a file on the screen. Type:
$ cat science.txt
As you can see, the file is longer than the size of the window, so it scrolls past making it unreadable.
less
The command less writes the contents of a file onto the screen a page at a time. Type
$ less science.txt
Press the [space-bar] if you want to see another page, and type [q] if you want to quit reading. As
you can see, less is used in preference to cat for long files.
head
The head command writes the first ten lines of a file to the screen.
First clear the screen then type
$ head science.txt
Then type
$ head -5 science.txt
Displays first 5 lines from the text file.
tail
The tail command writes the last ten lines of a file to the screen.
Clear the screen and type
$ tail science.txt
10. Searching the Contents of a File
Simple searching using less
17. 15
Using less, you can search though a text file for a keyword (pattern). For example, to search
through science.txt for the word 'science', type
$ less science.txt
then, still in less, type a forward slash [/] followed by the word to search
/science
As you can see, less finds and highlights the keyword. Type [n] to search for the next occurrence of
the word.
grep
grep is one of many standard UNIX utilities. It searches files for specified words or patterns.
First clear the screen, then type
$ grep science science.txt
As you can see, grep has printed out each line containing the word science.
Or has it ????
Try typing
$ grep Science science.txt
The grep command is case sensitive; it distinguishes between Science and science.
To ignore upper/lower case distinctions, use the -i option, i.e. type
$ grep -i science science.txt
To search for a phrase or pattern, you must enclose it in single quotes (the apostrophe
symbol). For example to search for spinning top, type
$ grep -i 'spinning top' science.txt
Some of the other options of grep are:
-v display those lines that do NOT match
-n precede each matching line with the line number
-c print only the total count of matched lines
Try some of them and see the different Results. Don't forget, you can use more than one option at a
time. For example, the number of lines without the words science or Science is
$ grep -ivc science science.txt
wc (word count)
A handy little utility is the wc command, short for word count. To do a word count on
science.txt, type
$ wc -w science.txt
To find out how many lines the file has, type
$ wc -l science.txt
11. Redirection
Most processes initiated by UNIX commands write to the standard output (that is, they write
to the terminal screen), and many take their input from the standard input (that is, they read it from
the keyboard). There is also the standard error, where processes write their error messages, by
default, to the terminal screen.
We have already seen one use of the cat command to write the contents of a file to the screen.
Now type cat without specifying a file to read
$ cat
Then type a few words on the keyboard and press the [Return] key.
Finally hold the [Ctrl] key down and press [d] (written as ^D for short) to end the input.
What has happened?
18. 16
If you run the cat command without specifying a file to read, it reads the standard input (the
keyboard), and on receiving the 'end of file' (^D), copies it to the standard output (the screen).
In UNIX, we can redirect both the input and the output of commands.
12. Redirecting the Output
We use the > symbol to redirect the output of a command. For example, to create a file
called list1 containing a list of fruit, type
$ cat > list1
Then type in the names of some fruit. Press [Return] after each one.
pear
banana
apple
^D {this means press [Ctrl] and [d] to stop}
What happens is the cat command reads the standard input (the keyboard) and the > redirects the
output, which normally goes to the screen, into a file called list1.
To read the contents of the file, type
$ cat list1
13. Appending to a File
The form >> appends standard output to a file. So to add more items to the file list1, type
$ cat >> list1
Then type in the names of more fruit
peach
grape
orange
^D (Control D to stop)
To read the contents of the file, type
$ cat list1
Create a file called list2 containing fruit names. We will now use the cat command to join
(concatenate) list1 and list2 into a new file called biglist. Type
$ cat list1 list2 > biglist
Here reading the contents of list1 and list2 in turn, then outputting the text to the file biglist .
To read the contents of the new file, type
$ cat biglist
14. Redirecting the Input
We use the < symbol to redirect the input of a command.
The command sort alphabetically or numerically sorts a list. Type
$ sort
Then type in the names of some animals. Press [Return] after each one.
dog
cat
bird
ape
^D (control d to stop)
The output will be
ape
bird
19. 17
cat
dog
Using < you can redirect the input to come from a file rather than the keyboard. For example, to sort
the list of fruit, type
$ sort < biglist
and the sorted list will be output to the screen.
To output the sorted list to a file, type,
$ sort < biglist > slist
Use cat to read the contents of the file slist
15. Pipes
To see who is on the system with you, type
$ who
One method to get a sorted list of names is to type,
$ who > names.txt
$ sort < names.txt
This is a bit slow and you have to remember to remove the temporary file called names when
you have finished. What you really want to do is connect the output of the who command directly to
the input of the sort command. This is exactly what pipes do. The symbol for a pipe is the vertical
bar |
For example, typing
$ who | sort
will give the same Result as above, but quicker and cleaner.
To find out how many users are logged on, type
$ who | wc -l
16. Wildcards
The * wildcard
The character * is called a wildcard, and will match against none or more character(s) in a file
(or directory) name. For example, in your student directory, type
$ ls list*
This will list all files in the current directory starting with list....
Try typing
$ ls *list
This will list all files in the current directory ending with ....list
The ? wildcard
The character ? will match exactly one character.So ?ouse will match files like house and
mouse, but not grouse.
% ls ?list
17. Getting Help
On-line Manuals
There are on-line manuals which gives information about most commands. The manual
pages tell you which options a particular command can take, and how each option modifies the
behavior of the command. Type man command to read the manual page for a particular command.
For example, to find out more about the wc (word count) command, type
$ man wc
20. 18
Alternatively
$ whatis wc
gives a one-line description of the command, but omits any information about options etc.
18. File System Security (Access Rights)
In your student directory, type
$ ls -l (l for long listing!)
You will see that you now get lots of details about the contents of your directory, similar to the
example below.
Each file (and directory) has associated access rights, which may be found by typing ls -l. Also, ls
-lg gives additional information as to which group owns the file (beng95 in the following example):
-rwxrw-r-- 1 ee51ab beng95 2450 Sept29 11:52 file1
In the left-hand column is a 10 symbol string consisting of the symbols d, r, w, x, -, and,
occasionally, s or S. If d is present, it will be at the left hand end of the string, and indicates a
directory: otherwise - will be the starting symbol of the string.
The 9 remaining symbols indicate the permissions, or access rights, and are taken as three groups of
3.
The left group of 3 gives the file permissions for the user that owns the file (or directory)
(ee51ab in the above example);
the middle group gives the permissions for the group of people to whom the file (or directory)
belongs (eebeng95 in the above example);
the rightmost group gives the permissions for all others.
The symbols r, w, etc., have slightly different meanings depending on whether they refer to a simple
file or to a directory.
Access rights on files
r (or -), indicates read permission (or otherwise), that is, the presence or absence of permission
to read and copy the file
w (or -), indicates write permission (or otherwise), that is, the permission (or otherwise) to
change a file
x (or -), indicates execution permission (or otherwise), that is, the permission to execute a file,
where appropriate
Access rights on directories
21. 19
r allows users to list files in the directory;
w means that users may delete files from the directory or move files into it;
x means the right to access files in the directory. This implies that you may read files in the
directory provided you have read permission on the individual files.
So, in order to read a file, you must have execute permission on the directory containing that file, and
hence on any directory containing that directory as a subdirectory, and so on, up the tree.
Some examples
-rwxrwxrwx a file that everyone can read, write and execute (and delete).
-rw-------
a file that only the owner can read and write - no-one else
can read or write and no-one has execution rights (e.g. your
mailbox file).
19. Changing Access Rights
chmod (changing a file mode)
Only the owner of a file can use chmod to change the permissions of a file. The options of chmod
are as follows
Symbol Meaning
U user
G group
O other
A all
R read
W write (and delete)
X execute (and access directory)
+ add permission
- take away permission
For example, to remove read write and execute permissions on the file biglist for the group and
others, type
$ chmod go-rwx biglist
This will leave the other permissions unaffected.
To give read and write permissions on the file biglist to all,
$ chmod a+rw biglist
Other useful UNIX commands
find
This search through the directories for files and directories with a given name, date, size, or
any other attribute you care to specify. It is a simple command but with many options - you can read
the manual by typing man find.
To search for all fies with the extention .txt, starting at the current directory (.) and working
through all sub-directories, then printing the name of the file to the screen, type
22. 20
$ find . -name "*.txt" -print
To find files over 1Mb in size, and display the Result as a long listing, type
$ find . -size +1M -ls
history
The C shell keeps an ordered list of all the commands that you have entered. Each command
is given a number according to the order it was entered.
$ history (show command history list)
If you are using the C shell, you can use the exclamation character (!) to recall commands easily.
$ !! (recall last command)
$ !-3 (recall third most recent command)
$ !5 (recall 5th command in list)
$ !grep (recall last command starting with grep)
20. UNIX Variables
Variables are a way of passing information from the shell to programs when you run them.
Programs look "in the environment" for particular variables and if they are found will use the values
stored. Some are set by the system, others by you, yet others by the shell, or any program that loads
another program.
Standard UNIX variables are split into two categories, environment variables and shell
variables. In broad terms, shell variables apply only to the current instance of the shell and are used
to set short-term working conditions; environment variables have a farther reaching significance, and
those set at login are valid for the duration of the session. By convention, environment variables have
UPPER CASE and shell variables have lower case names.
Environment Variables
An example of an environment variable is the OSTYPE variable. The value of this is the
current operating system you are using. Type
$ echo $OSTYPE
More examples of environment variables are
USER (your login name)
HOME (the path name of your home directory)
HOST (the name of the computer you are using)
ARCH (the architecture of the computers processor)
DISPLAY (the name of the computer screen to display X windows)
PRINTER (the default printer to send print jobs)
PATH (the directories the shell should search to find a command)
Finding out the current values of these variables.
ENVIRONMENT variables are set using the setenv command, displayed using the printenv or env
commands, and unset using the unsetenv command.
To show all values of these variables, type
$ printenv | less
Shell Variables
An example of a shell variable is the history variable. The value of this is how many shell commands
to save, allow the user to scroll back through all the commands they have previously entered. Type
$ echo $history
More examples of shell variables are
23. 21
cwd (your current working directory)
home (the path name of your home directory)
path (the directories the shell should search to find a command)
prompt (the text string used to prompt for interactive commands shell your login shell)
Finding out the current values of these variables.
SHELL variables are both set and displayed using the set command. They can be unset by using the
unset command.
To show all values of these variables, type
$ set | less
Unix Command Summary
cat --- for creating and displaying short files
chmod --- change permissions
cd --- change directory
cp --- for copying files
date --- display date
echo --- echo argument
ftp --- connect to a remote machine to download or upload files
grep --- search file
head --- display first part of file
ls --- see what files you have
lpr --- standard print command (see also print )
more --- use to read files
mkdir --- create directory
mv --- for moving and renaming files
print --- custom print command (see also lpr )
pwd --- find out what directory you are in
rm --- remove a file
rmdir --- remove directory
sort --- sort file
tail --- display last part of file
telnet --- log in to another machine
wc --- count characters, words, lines
24. 22
D.2 SHELL PROGRAMMING
Ex. No: 2.1
Date:
Implementation of shell program to find area and circumference of circle
Aim:
To write a shell program for finding area and circumference of circle.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read radius.
2. Calculate area and circumference by using the formula given below;
Area=(3.14*r*r)
Circumference =(2*3.14*r)
3. Display area and circumference of circle.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program for finding area and circumference of circle was written, executed and
output verified successfully.
25. 23
Ex. No: 2.2
Date:
Implementation of shell program to find simple interest
Aim:
To write a shell program to find simple interest.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read p- Principal amount, r-Rate of interest and n- Number of years (PNR).
2. Calculate simple interest by using the formula given below;
SI=(p*n*r)/100
3. Display simple interest.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to find simple interest was written, executed and output verified
successfully.
26. 24
Ex. No: 2.3
Date:
Implementation of shell program to find greatest of three numbers
Aim:
To write a shell program for finding greatest of three numbers.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read three numbers a,b,c.
2. Check if „a‟ is greater than both ‟b‟ and „c‟
a) If yes
Display „a‟ is greater
Go to step 3
b) Otherwise
Check if „b‟ is greater than both „a‟ and „c‟
a) If yes
Display „b‟ is greater
Go to step 3
b) Otherwise
Display „c‟ is greater
Go to step 3
3. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to find greatest of three numbers was written, executed and output
verified successfully.
Ex. No: 2.4
Date:
27. 25
Implementation of shell program to check a year as leap or not
Aim:
To write a shell program to check a year as leap or not.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read year.
2. Check if year is divisible by 4
2.a) If yes
Display year as „leap year‟
Go to Step 3
2.b) Otherwise
Display year as „not leap year‟
Go to Step 3
3. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to check a year as leap or not was written, executed and output
verified successfully.
28. 26
Ex. No: 2.5
Date:
Implementation of shell program to display student grade
Aim:
To write a shell program to display student grade.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read the student marks.
2. Calculate the average and total by using formula given below,
Tot = (m1+m2+m3+m4+m5)
Avg = tot/5
3. Check if the marks are greater than 50,
3.1) If greater than 50
Display „PASS‟
Go to Step 4
3.2) Otherwise
Display „FAIL‟
Go to Step 4
4. Check avg as above 75,
4.1)Print „FIRST CLASS‟
4.2)Go to Step 7
5. Check avg as above 60,
5.1)Print‟ SECOND CLASS‟
5.2)Go to Step 7
6. Check avg as above 50,
6.1)Print „THIRD CLASS‟
6.2)Go to Step 7
7. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to display student grade was written, executed and output verified
successfully.
29. 27
Ex. No: 2.6
Date:
Implementation of shell program to find factorial of a given number
Aim:
To write a shell program to find factorial of a given number.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read a number to which factorial to be found.
2. Initialize variable f as 1.
3. While there are still elements to be processed, do the following;
3.1) If yes calculate factorial as
n! = n*(n-1)
Go to Step 4
3.2) Otherwise
Go to Step 4
4. Display factorial.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to find factorial of given number was written, executed and output
verified successfully.
30. 28
Ex. No: 2.7
Date:
Implementation of shell program to generate fibonacci series
Aim:
To write a shell program to generate fibonacci series.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read the limit up to which fibonacci series to be generated.
2. Initialize first two terms as a=0, b=1.
3. While there are still elements to be generated, do the following;
3.1) If yes
Calculate new term c by adding previous two terms(c=a+b)
Print the term
Update two term by reassigning a=b, b=c
Go to Step 3
3.2) Otherwise
Go to Step 4
4. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to generate fibonacci series was written, executed and output verified
successfully.
31. 29
Ex. No: 2.8
Date:
Implementation of shell program to check a number as prime or not
Aim:
To write a shell program to check a number as prime or not.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read a number as n which is to be checked as prime or not.
2. While there are still factors to be analyzed, do the following;
2.1) Check the divisibility of the number by continuously from i=2 to mod(n/i)=0
If yes
Go to Step 3
Otherwise
Go to step 2
3. Check whether the number do not have factor,
If Yes
Print the number as prime
Otherwise
Print the number as not prime
4. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to check a number as prime or not was written, executed and output
verified successfully.
32. 30
Ex. No: 2.9
Date:
Implementation of shell program to check a number as palindrome or not
Aim:
To write a shell program to check a number as palindrome or not.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read a number which is to be checked as palindrome or not.
2. Make a copy of the number in another buffer as n.
3. Initialize rev as 0.
4. While there are still elements to be processed do the following;
4.1) If yes
Get the remainder by using modulo 10
Update the value of rev by adding remainder with rev after multiplying by
10
Reduce the number dividing it by 10
Go to Step 4
4.2) Otherwise
Go to Step 5
5. Check whether original number and rev number are equal
5.1) If yes, print the number as palindrome
5.2) Otherwise, print the number as not palindrome
6. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to check a number as palindrome or not was written, executed and
output verified successfully.
33. 31
Ex. No: 2.10
Date:
Implementation of shell program to check a number as armstrong or not
Aim:
To write a shell program to check a number as armstrong or not.
Environment Required:
Hardware : Unix Workstation
Software : Shell
Algorithm:
1. Read a number which is to be checked as armstrong or not.
2. Assign sum=0 and rem=0.
3. Copy the current value of number to n.
4. While there are still elements to be processed;
4.1) If yes
Extract the value rem by using modulo function
Update the value of sum by adding the current value of sum with cubic
value of rem
Reduce the number by using operator(div 10)
Go to Step 4
4.2) Otherwise
Go to Step 5
5. Check if original number and sum as equal
5.1) If yes
Print the given number as armstrong
Go to Step 6
5.2) Otherwise
Print the given number as not armstrong
Go to Step 6
6. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the shell program to check a number as Armstrong or not was written, executed
and output verified successfully.
34. 32
D.3 SYSTEM CALLS & I/O SYSTEM CALLS
Ex. No: 3.1
Date:
Implementation of C programs using the following system calls of UNIX operating system fork (),
getpid (), getppid (), wait (), exit (), opendir(), readdir(), closedir()
Aim:
To write C programs using the following system calls of UNIX operating system fork (),
getpid (), getppid (), wait (), exit (), opendir (), readdir (), closedir ().
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
Process:
A program in execution is said to be a process. When we boot the system, a special process
called the swapper or the scheduler is created with a PID of 0.The swapper manages the memory
allocation for process and influences the CPU allocation. The swapper in turn creates three children,
the process dispatcher, vhand and bdflush with id numbers 1, 2, 3 respectively. This is done by
executing the files init which exits in the exec subdirectory. The process dispatcher gives birth to the
shell. Now all processes initiated by us are the children of the shell and in turn descendents of the
process dispatcher. UNIX keeps track of all process in an internal data structure called the
PROCESS TABLE. A listing of the process table can be got using the ps –el command.
Background Process:
A process which takes more time for execution and during which the computer becomes
inaccessible can be made as background process. To create a background process the program is
compiled at the UNIX prompt using the command “cc <program name>>”.This will generate a file
a.out. This file is executed using the command “. /a.out &”. The „&‟ will make the process as
background process which is terminated only if the process ends it is interrupted with DELL. The
programs that don‟t take input or print to the screen must be made as background process.
Orphan Process:
When the parent process terminates before the child process, then the child process becomes
an orphan process. After a fork function, the time slice is given to the child process. If the child
process is made to sleep, then time slice goes to the parent process and the parent after execution
which terminates. Now the child process becomes an orphan process. The orphan process is
immediately adopted by the process dispatcher.
35. 33
Zombie Process:
When the child process terminates before the parent process, then the child process is not
removed from the PROCESS TABLE and the child becomes a zombie process. After a fork, if the
child terminates after executing a few steps and the parent is still executing for some time then the
child process becomes a zombie process.
Sleeping Process:
A process which is made to sleep using the sleep function is said to be a sleeping process.
System Calls:
a) fork ():
The fork function is used for creating child processes. The fork () creates a child which is a
duplicate of the parent process. The child process begins from the fork (). All other statements after
the fork will be executed twice, once by the parent and once by the child process. If there are
statements before fork they will be executed only by the parent process. The moment a call is made to
the fork (), a child process is created. The child too gets a copy of the variable PID, but with a default
value of 0.The parent process will return a value .This value greater than 0 which is returned by child
process. If the fork is unable to create a child process due to memory problem the variable PID of the
parent process will contain -1, indicating an error.
b) getpid ():
Syntax: int getpid () - Enables to get the identification number of the process.
c) getppid ():
Syntax: int getppid () - Enables to get the identification number of the parent.
d) wait ():
When a call to a wait function is made, it checks if the parent process has any children. If there
are no children -1 is returned by the wait ().If the parent process has a child that has terminated, then
the child‟s PID is returned and it is removed from the PROCESS TABLE. If the parent has a child or
children that have not terminated, the parent process is suspended till it receives a signal. The signal is
received as soon as the child dies.
e) exit ():
The exit () function terminates a process and removes it from the PROCESS TABLE.
f) opendir ():
36. 34
Syntax: DIR *dir;
dir=opendir (directory name);
The opendir function opens the directory specified and returns a pointer which is assigned to
dir name.
g) readdir ():
Syntax: struct dirent * rddir
rddir=readdir (dir name);
The readdir function reads the name of the first file from the opened directory. The readdir()
function is passed to the starting location of this directory as a parameter.
h) closedir ():
Syntax: closedir (dir name);
The closedir () function closes the opened directory.
Source Code:
<To be prepared by student>
Result:
Thus, the C programs using system calls of the UNIX operating system were written, executed
and output verified successfully.
37. 35
Ex. No: 3.2
Date:
Implementation of C programs using the following I/O system calls of UNIX operating system
open (), close (), read (), write()
Aim:
To write C programs using the following I/O system calls of UNIX operating system
open (), close (), read (), write ().
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
a) open():
The open() system call is used to convert a path name into a file description. If the call is
successful, then the file description will be returned. The open function can be invoked as following,
int open (const char * pathname, int flags);
int open (const char * pathname, int flags, mode_t mode);
return value:
If the opening and creation are successful, a new file description is returned otherwise –l is
returned if an error occurred.
b) close():
The close() function closes a file description, so that it no longer refers to any files and may be
reused. Any clocks held on the file it was associated with and owned by the process are removed. The
close function can be invoked as follows,
int close (int fd);
return value:
close() returns zero on success and return -1 on failure if an error occurred.
c) read():
38. 36
read() attempts to read upto n bytes from the file description into the buffer starting at buffer.
If count is zero read() returns zero and has no other Results. If count is greater than size _max the
Result is unspecified. The read function can be invoked as follows,
int read (int fd, void * buff, int count);
return value:
On success the function read returns the number of bytes (zero indicates end of file) and file
position is advanced by this number. It is not an error, if the reposition number is smaller than
number of bytes returned.
On error, -1 is returned and err no is set appropriately.
d) write():
write() writes upto count bytes to the file referenced by the file descriptor from the buffer
starting at buffer. The write function can be invoked as follows,
int write(int fd,void *buff,int count);
return value:
On success the function write returns the number of bytes(Zero indicates nothing was
written).It is not an error, if the reposition number is smaller than number of bytes returned.
On error,-1 is returned and error is set appropriately.
Source Code:
<To be prepared by student>
Result:
Thus, the C programs using I/O system calls of the UNIX operating system were written,
executed and output verified successfully.
39. 37
D.4 SIMULATION OF UNIX COMMAND
Ex. No: 4
Date:
Implementation of C program to simulate UNIX command - LS
Aim:
To write C program to simulate the function of LS command.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Simulation of LS:
Algorithm:
1. Get the directory to be listed through command line arguments.
2. Open the directory using opendir() function.
3. While there are files to be processed, do the following;
i. Read the file from the directory using readdir().
ii. Print the file name.
Source Code:
<To be prepared by the student>
Result:
Thus the C program for the simulation of LS command was written, executed and output
verified successfully.
40. 38
D.5 CPU SCHEDULING ALGORITHMS
Ex. No: 5.1
Date:
Implementation of first come first serve scheduling algorithm
Aim:
To write a C program to implement first come and first serve scheduling algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
CPU SCHEDULING:
CPU scheduling is a process which allows one process to use the CPU while the
execution of another process is on hold (in waiting state) due to unavailability of any resource like I/O
etc, thereby making full use of CPU. The Aim of CPU scheduling is to make the system efficient, fast
and fair.
FIRST COME AND FIRST SERVE:
FCFS is pre-emptive scheduling Algorithm. If process first arrived is a big process
with a high burst time, then other processes with less burst time need to wait. Average wait time is
high.
Algorithm:
1. Get the number of processes, along with their arrival and burst times.
2. Sort the process in the increasing order of the arrival time.
3. For all process do the following;
3.1) Calculate the waiting time of each process as the difference of the process arrival
time and finishing of previous process
3.2) Calculate the turnaround time of each process as the addition of its waiting and
CPU burst times
4. Calculate the average of both waiting time and turnaround time.
5. Display the process number, arrival time, burst time, turnaround time, waiting
time, average turnaround time and average waiting time.
6.Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program for implementing the first come first serve scheduling algorithm was
written, executed and output verified successfully.
41. 39
Ex. No: 5.2
Date:
Implementation of shortest job first scheduling algorithm
Aim:
To write a C program to implement shortest job first scheduling algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
SHORTEST JOB FIRST:
Shortest Job Firstt (SJF), also known as Shortest Job Next (SJN) or Shortest
Process Next(SPN), is a scheduling policy that selects for execution the waiting process with the
smallest execution time. SJN is a non-preemptive.
Algorithm:
1. Get the number of processes, with their arrival and burst time.
2. Check if all the processes arrival time is equal;
2.1) If yes, sort the processes in the increasing order of burst time
(A) For all the process, do the following
Calculate the waiting time of each process as how long it has been waited
by other processes
Calculate the turnaround time of each process as the addition of its
waiting and CPU burst time
Go to step3
2.2) Otherwise
(B) While there are still processes, do the following
Schedule the process which arrived first
Check at every milliseconds, whether there is any new process with shorter
burst time
a) If yes
Schedule the newly process in the CPU and reduce the burst time of
previous process by its executed milliseconds. And calculate its waiting
time as how long it has been waited by other processes
Go to step no 2.2.B
b) Otherwise
Compute the execution of currently running process, and assign its waiting
time as 0
Go to step no 2.2.B
2.3) Calculate the turnaround time as the addition of its waiting and CPU burst times
3. Calculate the average of both waiting time and turnaround time.
4. Display the process number, arrival time, burst time, turnaround time, waiting
time, average turnaround time and average waiting time.
42. 40
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program for implementing the shortest job first scheduling algorithm was written,
executed and output verified successfully.
43. 41
Ex. No: 5.3
Date:
Implementation of priority scheduling algorithm
Aim:
To write a C program to implement priority scheduling algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
Priority scheduling is a method of scheduling processes based on priority. Priority
scheduling involves priority assignment to every process and processes with higher priorities are
carried out on a First Come First Serve(FCFS).
Algorithm:
1. Get the no of processes, with their arrival, burst time and priority.
2. Check if all the processes arrival time is equal;
2.1) If yes, sort the processes in the increasing order of priority
(A) For each processes do the following
Calculate the waiting time of each process as how long it has been waited by
other processes
Calculate the turnaround time of each process as how long it has the addition
of its waiting and CPU burst time
Go to step no 3
2.2) If no
(B) While there are still processes, do the following
Schedule the process which arrived first
Check at every milliseconds, whether there is any new process with higher
priority. (smaller number means higher priority)
a) If yes
Schedule the new process in the CPU and reduce the burst time of previous
process by its executed milliseconds. And calculate finally its waiting time as
how long it has been waited by other processes
Go to step no 2.2.B
b) Otherwise
44. 42
Compute the execution time of running process. And assign its waiting time as
0
Go to step no 2.2.B
2.3) Calculate the turnaround time as the addition of its waiting and CPU burst
time
3. Calculate the average of both waiting time and turnaround time.
4. Display the process number, arrival time, burst time, turnaround time, waiting
time, average turnaround time and average waiting time.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program for implementing the priority scheduling algorithm was written, executed
and output verified successfully.
45. 43
Ex. No: 5.4
Date:
Implementation of round robin scheduling algorithm
Aim:
To write a c program to implement round robin scheduling algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
Round Robin (RR) is one of the Algorithms employed by process and network schedulers
in computing. RR is simple, easy to implement starvation-free. RR scheduling can also applied to
other scheduling problem.
Algorithm:
1. Get the number of processes, with their time slice, their arrival and burst times.
2. Sort the processes in the increasing order of arrival time.
3. For each process do the following;
A) Check if burst time of process is lesser than time slice,
a) If yes,
After completion of its execution, schedule next process,
Go to step no 3
b) Otherwise,
After time slice expires, schedule next process,
Go to step no 3
B) Calculate finally each processes waiting time as how long it has been waited by
other processes
C) Calculate the turnaround time of each process as the addition of its waiting and
CPU burst time
4. Calculate the average of both waiting time and turnaround time.
5. Display the process number, arrival time, burst time, turnaround time, waiting
time, average turnaround time and average waiting time.
6. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program for implementing round robin scheduling algorithm was written,
executed and output verified successfully.
46. 44
D.6 PROCESS SYNCHRONISATION
Ex. No: 6
Date:
Implementation of semaphores concept
Aim:
To write a C program to implement semaphores concept.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
Process synchronization means sharing system resources by process in such a way that,
concurrent access to shared data is handled thereby minimizing the chance of inconsistent data.
Algorithm:
1. Initialize the semaphores mutex,buffer full,buffer empty=x.
2. In producer process;
2.1) produce an item into buffer
2.2) If buffer is empty, then check the mutex value to enter the critical section
2.3) If the mutex value is 0, allow the producer to add value in the temporary variable
to the buffer
3. In consumer process;
3.1) It should wait if buffer is empty
3.2) If there is any item in the buffer, check the mutex value.
3.3) If the mutex=0, remove item from buffer.
3.4) Signal the mutex value and reduce the empty value by 1
3.5) Consume the item
4. Print the item.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement semaphores concept was written, executed and output
verified successfully.
47. 45
D.7 SHARED MEMORY AND INTERPROCESS COMMUNICATION
Ex. No: 7
Date:
Implementation of shared memory and interprocess communication concept
Aim:
To write a C program to implement interprocess communication concept.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
SHARED MEMORY:
Shared memory is memory that may be simultaneously accessed by multiple
programs. Shared memory is an efficient means of passing data between programs.
INTERPROCESS COMMUNICATION:
IPC is as set of programming interface that allow a programmer to coordinate
actives among different program processes that can run concurrently in operating system.
Algorithm:
1. Create shared memory for parent process using shmget() system call.
2. Allow the parent process to write in shared memory using shmat().
3. Now allow the child process to read data from the shared memory using shmat().
4. Now, detach and reduce the shared memory.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement interprocess communication concept was written,
executed and output verified successfully.
48. 46
D.8 DEADLOCK DETECTION ALORITHM
Ex. No: 8
Date:
Implementation of banker‟s algorithm for deadlock detection
Aim:
To write a C program to implement banker‟s algorithm for deadlock detection.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
Deadlock Detection is the process of actually determining that a deadlock exists and
identifying the processes and resources involved in the deadlock. A deadlock is a situation in which
two computers program sharing the same resources are effectively preventing each other from
accessing the resources Resulting both program ceasing to function.
Algorithm:
1. Assign work = available and finish be the vectors
2. While there are still processes to be checked, do the following;
2.1) Check if allocation as i!= 0
If yes,
Assign finish[i] as false
Otherwise
Assign finish[i] as true
3. Find an index[i] such that both finish[i]=false and request[i] <= work;
Otherwise
Go to step 4
If yes
a) Update work = work + allocation
b) Finish[i] = true
c) Go to step 3
4. If finish[i]=false for some i, the value of i is 1<=i<=x then print as system is in
deadlock, and corresponding process is in deadlock state.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement banker‟s algorithm for deadlock detection was written,
executed and output verified successfully.
49. 47
D.9 DEADLOCK AVOIDANCE ALGORITHM
Ex. No: 9
Date:
Implementation of banker‟s algorithm for deadlock avoidance
Aim:
To write a C program to implement banker‟s algorithm for deadlock avoidance.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Description:
Deadlock avoidance Algorithms try not to allocate resources to a process if it will make
the system in an unsafe state. An edge from a process to resource is request edge and an edge from a
resource to process is an allocation edge.
Algorithm:
1. Assign work and finish[i] are the vectors also initialize work = available then make
finish[i] as false.
2. Find an index i such that both finish[i] = false and need[i]<=available;
Otherwise
Go to step 4
If yes
a) Update work = work + allocation
b) Finish[i] = true
c) Go to step 3
3. If finish [i] = true for all i, then print the system is in safe state.
4. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement banker‟s algorithm for deadlock avoidance was written,
executed and output verified successfully.
50. 48
D.10 THREADING
Ex. No: 10
Date:
Implementation of multithreading concept
Aim:
To write a C program for implementing multithreading concept.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
Multithreading is the ability of a program or an operating system process to manage its use
by more than one user at a time and to even manage multiple request by the same user without having
to have multiple copies of the programming running in the computer.
Algorithm:
1. Initialize the buffer index and allocate the memory dynamically.
2. Create a thread to each producer and consumer process.
3. Producer locates thread mutex as locked to place data until buffer reaches the
maximum in size. And then release thread as unlocked once the buffer is full.
4. Consumer locates thread mutex as locked to consume data until the buffer is empty.
And then release thread as unlocked once the buffer becomes empty.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program for implementing multithreading concept was written, executed and
output verified successfully.
51. 49
D.11 MEMORY ALLOCATION METHODS FOR FIXED PARTITION
Ex. No: 11
Date:
Implementation of first fit, best fit and worst fit memory allocation methods for fixed partition
Aim:
To write C programs to implement the first fit, best fit and worst fit memory allocation
methods for fixed partition.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
Algorithm:
1. Read the number of partitions and the partitions size.
2. Read the number of processes and their sizes.
3 Read the memory allocation strategy
4 Check if the strategy is first fit;
A) If Yes, while there are still processes to be allocated;
i) Search the partitions list which has the first hole that is big enough
ii) If such a partition is found allocate the process to that partition
And go to step 4A
iii) If no such partition is found go to step 4A.
B) Otherwise, go to step 5
5. Check if the strategy is Best Fit;
A) If Yes, while there are still processes to be allocated;
i) Arrange the partitions in the increasing order with respect to its size
ii) Search the partitions list which has smallest hole that is big enough
iii) If such a partition is found allocate the process to that partition
And go to step 5A
iv) If no such partition is found go to step 5A.
B) Otherwise, go to step 6
6. Check if the strategy is worst fit,
A) If Yes, while there are still processes to be allocated,
i) Arrange the partitions in the decreasing order with respect to its size.
ii) Search the partitions list which has largest hole that is big enough.
ii) If such a partition is found allocate the process to that partition.
And go to step 6A
iv) If no such partition is found Go to step 6A .
B) Otherwise, go to step 7.
7. Stop.
52. 50
Source Code:
<To be prepared by the student>
Result:
Thus the C programs for implementing the first fit, best fit, worst fit memory allocation
methods for fixed partition were written, executed and output verified successfully.
53. 51
D.12 PAGING TECHNIQUE
Ex. No: 12
Date:
Implementation of paging technique of memory management
Aim:
To write a C program to implement paging technique of memory management.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
Paging is a memory management scheme by which a computer stores and retrieves
data from secondary storage in same size blocks for use in main memory.
Algorithm:
1. Read the logical memory address.
2. Read the page table along with the offset and page frame.
3. Calculate the physical address by using formulae
PA= [page frame *no of paging] +page offset
4. Print the physical address for the corresponding logical address.
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement paging technique of memory management was written,
executed and output verified successfully.
54. 52
D.13 PAGE REPLACEMENT ALGORITHMS
Ex. No:13.1
Date:
Implementation of FIFO page replacement algorithm
Aim:
To write a C program to implement FIFO page replacement algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
PAGE REPLACEMENT:
A page replacement Algorithm is set to satisfy the inclusion property called stack
Algorithm. When there is a page fault, the referenced page must be loaded. If there is no available in
memory then, one page is selected for replacement.
Algorithm:
1. Declare the frame size.
2. Make the frames to be empty.
3. The reference is bought into the frames in FIFO manner
3.1) First references are bought into empty frames page faults
3.2) Remaining frames are checked with the existing the frames.
3.3) If it is available, then no page fault
3.4) If it is not available, then page fault occurs. Replace the reference
in the next frame with the current reference
4. Select the page which the frames are comes in the first
5. Repeat the above process until all reference is allocated
6. Stop.
Source Code:
< To be prepared by student >
Result:
Thus, the C program to implement FIFO page replacement algorithm was written, executed
and output verified successfully.
55. 53
Ex. No: 13.2
Date:
Implementation of LRU page replacement algorithm
Aim:
To write a C program to implement LRU page replacement algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
LEAST RECENTLY USED:
On a page fault, frame that was least recently used is replaced. Pages with a
current copy on disk are first choice for pages to be removed when more memory is needed.
Algorithm:
1. Declare the frame size
2. All the frames are initially empty
3. The reference is brought into the frames one by one
3.1) First reference are brought into empty frames page faults
3.2) Remaining frames are checked with the existing the frames
3.3) If it is available, then no page fault
3.4) If it is not available, then page fault occurs. Replace the page that has not been
used for the longest period of time with current reference
4. Select the page which is not recently used
5. Repeat the above process until all reference is allocated
6. Stop.
Source Code:
< To be prepared by student >
Result:
Thus, the C program to implement LRU page replacement algorithm was written, executed
and output verified successfully.
56. 54
Ex. No: 13.3
Date:
Implementation of LFU page replacement algorithm
Aim:
To write a C program to implement LFU page replacement algorithm.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
LEAST FRQUENCY USED:
LFU is a type of cache Algorithm used to manage memory with in a computer
when the cache is full and it requires more system will purge the item with the lowest reference
frequency.
Algorithm:
1. Declare the maximum page and frame size initially
2. Input the no of pages, no of frames and sequence for no of pages is the request
function
3. If all the frames are filled with pages
4. The next page is allocated at the place where the page is not used for longer period
time
5. Using the replace function replace the page when the page is not found in frames.
Otherwise hit the page
6. Finally calculate the page fault.
7. Stop.
Source Code:
< To be prepared by student >
Result:
Thus, the C program to implement LFU page replacement algorithm was written, executed
and output verified successfully.
57. 55
D.14 FILE ORGANIZATION TECHNIQUES
Ex. No: 14.1
Date:
Implementation of single level directory structure for file organization
Aim:
To write a C program to implement single level directory structure for file organization.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
DIRECTORY:
A Directory is a location for storing files on computer. Directories are found in a
hierarchical file system, such as LINUX, MS -DOS and UNIX. Directories are used to organize files.
SINGLE LEVEL DIRECTORY:
Single level directory system, all the files are placed in one directory. This is very
common on single user OS‟s. A single level directory has significant limitation.
Algorithm:
1. Read the number of directories, files
2. Create a root directory, user defined file
3. While there are still link to be created
If yes, do the following
Define link, attach the user files to it
Go to step 3
Otherwise
Go to step 4
4. Print the directory structure
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement single level directory for file organization was written,
executed and output verified successfully.
58. 56
Ex. No: 14.2
Date:
Implementation of two-level directory structure for file organization
Aim:
To write a C program to implement two-level directory structure for file organization.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
Two-level directory, each user gets one directory space. A master file directory is used to
track of each use directory.
Algorithm:
1. Read the number of directories, subdirectories and files
2. Create a root directory and define user defined link
3. Define while there are still link to be created
If yes, do the following
Define the link and attach to the subdirectories, file to it
Define null printer at the end of lower level file structure
Go to step 3
Otherwise
Go to step 4
4. Print the directory structure
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement two-level directory structure for file organization was
written, executed and output verified successfully.
59. 57
Ex. No: 14.3
Date:
Implementation of hierarchical level directory structure for file organization
Aim:
To write a C program to implement hierarchical level directory structure for file organization.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
The directory structure is the organization of files into a hierarchy of folder in single level
system, all the files are placed in one directory there is a root directory. It has a simple architecture and
there are no subdirectories.
Algorithm:
1. Read the number of directories, subdirectories and files
2. Create a root directory and define user defined link
3. While there are still link to be created,
If yes, do the following
Define the link and attach to the subdirectories, file to it
Define null printer at the end of lower level file structure
Go to step 3
Otherwise
Go to step 4
4. Print the directory structure
5. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement hierarchical level directory structure was written, executed
and output verified successfully.
60. 58
Ex. No: 14.4
Date:
Aim:
To write a C program to implement directed acyclic graph structure for file organization.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
Directed Acyclic Graph directories allows directory to link to one another, allow multiple
directory to contain same file two users can name same file or same directory copy of the file exists
and any changes in the file can be viewed by all directories.
Algorithm:
1. Read the name for root directory
2. Create a subdirectory under the present directory
3. Create a link under this directory
4. While there are still link to be created,
If yes, do the following
Define the line and under the required directory not to step 4
Otherwise
Go to step 4
5. Print the directory structure
6. Stop.
Source Code:
<To be prepared by student>
Result:
Thus, the C program to implement directed acyclic graph structure was written, executed and
output verified successfully.
Implementation of directed acyclic graph structure for file organization
61. 59
D.15 FILE ALLOCATION STRATEGIES
Ex. No: 15.1
Date:
Implementation of sequential file allocation strategy
Aim:
To write a C program to implement sequential file allocation strategy.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
FILE ALLOCATION:
The File Allocation defines how the files are stored in the disk blocks. It is used
by the operating system to manage files on hard device and other computer systems.
SEQUENTIAL STRATEGY:
The location of the file is defined by the disk address of the first and its length a
file allocated disk space using sequential allocation method.
Algorithm:
1. Declare the starting block and length of files initially
2. Get the input for the starting block and length of the file
3. If the block is not used, then it is allocated for the new one
4. Otherwise, print that the block is already allocated
5. If you want to add one more file
Go to step 2
Else
Go to step 6
6. Stop
Source Code:
< To be prepared by student >
Result:
Thus, the C program to implement sequential file allocation strategy was written, executed and
output verified successfully.
62. 60
Ex. No: 15.2
Date:
Implementation of indexed file allocation strategy
Aim:
To write a C program to implement indexed file allocation strategy.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
An Index block is created having all pointers to files. Each file has its own index block
which stores the address of disk space occupied by the file.
Algorithm:
1. Declare the index block
2. Read the number of files on index that are to be allocated of the index is empty, then
file is allocated to the index is already allocated
3. Repeat step 2 until the file is allocated
4. If you want to add one more file
Go to step 2
else
Go to step 5
5. Stop.
Source Code:
< To be prepared by student >
Result:
Thus, the C program to implement indexed file allocation strategy was written, executed and
output verified successfully.
63. 61
Ex. No: 15.3
Date:
Implementation of linked file allocation strategy
Aim:
To write a C program to implement linked file allocation strategy.
Environment Required:
Hardware : Unix Workstation
Software : C Compiler
DESCRIPTION:
In linked Allocation, each file is a linked list of disk blocks the directory contains a pointer
to the first and optionally the last block of the file. Disk blocks of a file are chained together with a
linked list.
Algorithm:
1. Declare the starting index block and length
2. Read the number of blocks that are already allocated
3. If entry any file in the block, if the file is exits, print the file in already allocated
4. If you want to add one more file
Go to step 2
Else
Go to step 5
5. Stop.
Source Code:
< To be prepared by student >
Result:
Thus, the C program to implement linked file allocation strategy was written, executed and
output verified successfully.
65. 63
Appendix - Source Code
SHELL PROGRAMMING
2.1. Implementation of shell program to find area and circumference of circle
Source Code:
echo-n“Enter Radius of the Circle:”
read r
area=$(echo“3-14*$r*$r”|bc-1)
cf=$(echo“2*3-14*$r”|bc-1)
echo “===================================”
echo “Area of Circle= $area”
echo “Circumference of Circle= $cf”
echo “===================================”
Output:
[cse@server2~]$ sh circle.sh
Enter Radius of the Circle:
10
=======================================
Area of Circle=314
Circumference of Circle= 62.8
=======================================
2.2. Implementation of shell program to calculate simple interest
Source code:
echo “Enter Principal amount, No of Years and Interest Rate:”
read p n r
si=$(echo “scale=2;$p*$n*$r/100”|bc)
Chapter
E
66. 64
echo “============================”
echo “Simple Interest = $si”
echo “============================”
Output:
[cse@server2~]$ sh si.sh
Enter Principal amount, No of Years and Interest Rate:
35000 5 100
=========================
Simple Interest = 175000
=========================
2.3. Implementation of shell program to find greatest of three numbers
Source code:
echo “Enter any three Integers A,B,C:”
read a b c
if [$a=gt $b=a $a-gt $c]
then
echo “$a is Greater”
elif [$b=gt $c]
then
echo “$b is Greater”
else
echo “$c is Greater”
fi
Output:
[cse@server2~]$ sh great.sh
Enter any three Integers A,B,C:
2 3 8
8 is Greater
67. 65
2.4. Implementation of shell program to check a year as leap or not
Source code:
echo -n “Enter any Year:”
read year
n=$(($year%4))
if[$n=eq 0]
then echo “The given Year $year is Leap Year”
else
echo “The given Year $year is not Lear Year”
fi
Output:
[cse@server2~]$sh leap.sh
Enter any Year : 2012
The given Year 2012 is Leap Year
2.5. Implementation of shell program to display student grade
Source code:
echo “Enter Mark for Five Subjects:”
read m1 m2 m3 m4 m5
tot=$(($m1+$m2+$m3+$m4+$m5))
average=$(echo“$tot/5”|bc-1)
avg=$average
if[$m1-lt 50-o $m2-lt 50-o $m3-lt 50-o $m4-lt 50-o $m5-lt 50]
then grade=“Fail”
elif [$echo “$avg>=75”|bcc)-eq 1]
then grade=“First Class with Distinction”
elif [$(echo “$avg>=60”|bc)-eq 1]
then grade=“First Class”
elif[$(echo “$avg>50”|bc)-eq 1]
then grade=“Second Class”
else
grade=“Third Class”
fi
68. 66
echo “=========================”
echo “Total Marks =$tot”
echo “Average Mark =$avg”
echo “Grade =$grade”
echo “=========================”
Output:
[cse@server2~]$ shstudent.sh
Enter Mark for Five Subjects:
90
93
93
95
91
=============================
Total Marks =463
Average Mark =92.6
Grade = First Class with Distinction
=============================
2.6. Implementation of shell program to find factorial of a given number
Source code:
echo –n “Enter any Integer:”
read n
f=1
for((i=1;1<$n;i++))
do
f=$(($f*$i))
done
echo “=======================”
echo “The Factorial of $n!=$f”
echo “======================”
Output:
69. 67
[cse@server21]$ sh fact.h
Enter any Integer:
5
===========================
The factorial of 5!=120
===========================
2.7. Implementation of shell program to generate fibonacci series
Source code:
echo –n “Enter the Limit for the Fibonacci Series:”
read n
a=0
b=1
echo “Fibonacci Series”
echo “===========================”
while [$a-le $n]
do
echo –n“$a”
c=$(($a+$b))
a=$b
b=$c
done
echo “==========================”
Output:
[cse@server2~]$ sh fib.sh
Enter the Limit for the Fibonacci Series:
10
Fibonacci Series
============================
0
1
1
2
70. 68
3
5
8
13
21
34
=============================
2.8. Implementation of shell program to check a number as prime or not
Source code:
echo –n “Enter any Integer:”
read num
for((i=2;i<$num%$i))-eq 0]
do
if[$(($num%$i))-eq 0]
then break;
fi
done
if[$i –eq $num –o $num –eq 1]
then echo “The given Number $num is a Prime”
else
echo “The given Number $num is not a Prime”
fi
Output:
[cse@server2~]$ sh prime.sh
Enter any Integer:
4
The Given Number 4 is not a Prime
[cse@server2~]$ sh prime.sh
Enter any Integer:
7
The given Number 7 is a Prime
2.9. Implementation of shell program to check a number as palindrome or not
Source Code:
71. 69
echo -n “Enter any Integer:”
read num
n=$num
rev=0
while [ $n -gt 0 ]
do
a=`expr $n % 10`
rev=`expr $rev * 10 + $a`
n=`expr $n / 10`
done
if [ $num -eq $rev ]
then echo “The number $num is Palindrome”
else
echo “The number $num is not Palindrome”
fi
Output:
[cse@server2~]$ sh palin.sh
Enter any Integer:
373
The Number 373 is a Palindrome
[cse@server2~]$ sh palin.sh
Enter any Integer:
371
The Number 371 is not a Palindrome
[cse@server2~]$
2.10. Implementation of shell program to check a number as armstrong or not
Source Code:
echo -n “Enter any Integer:”
read num
n=$num
arm=0
while [ $n -gt 0 ]
do
a=`expr $n % 10`
arm=`expr $arm + $a * $a * $a`
72. 70
n=`expr $n / 10`
done
if [ $num -eq $arm ]
then echo “The Number $num is an Armstrong”
else
echo “The Number $num is not an Armstrong”
fi
Output:
[cse@server2~]$ sh arm.sh
Enter any Integer:
371
The Number 371 is an Armstrong
[cse@server2~]$ sh arm.sh
Enter any Integer:
370
The Number 370 is not an Armstrong
[cse@server2~]$
SYSTEM CALLS & I/O SYSTEM CALLS
3.1. Implementation of C program using the following system calls of UNIX operating
system fork (), getpid (), getppid (), wait (), exit (), opendir (), readdir (), closedir ()
a.fork( )
Source Code:
#include<stdio.h>
main()
{
printf("Demo of Forkn");
fork();
printf("Hello!!!");
}
Output:
[cse@server2~]$ cc syscall1.c
[cse@server2~]$ ./a.out
Demo of Fork
73. 71
Hello!!![cse@server2~]$ Hello!!!
b.fork( )
Source Code:
#include<stdio.h>
main()
{
printf("Demo of Forkn");
fork();
fork();
printf("Hello");
}
Output:
[cse@server2~]$ cc syscall2.c
[cse@server2~]$ ./a.out
Demo of Fork
Hello[cse@server2~]$ HelloHelloHello
c. getpid( ) & getppid( )
Source Code:
#include<stdio.h>
main()
{
int pid;
pid=fork();
if(pid==0)
{
printf("Child Processn");
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
}
else
{
printf("Parent Processn");
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
74. 72
}
}
Output:
[cse@server2~]$ cc syscall3.c
[cse@server2~]$ ./a.out
Parent Process
getpid is 8794
getppid is 8617
[cse@server2~]$ Child Process
getpid is 8795
getppid is 1
d. orphan process
Source Code:
#include<stdio.h>
main()
{
int pid=fork();
if(pid==0)
{
printf("Child Processn");
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
sleep(20);
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
}
else
{
printf("Parent Processn");
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
}
}
Output:
[cse@server2~]$ cc syscall4.c
[cse@server2~]$ ./a.out
Parent Process
75. 73
getpid is 8841
getppid is 8617
Child Process
getpid is 8842
getppid is 1
e. zombie process
Source Code:
#include<stdio.h>
main()
{
int pid;
pid=fork();
if(pid==0)
{
printf("Child Processn");
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
}
else
{
sleep(20);
printf("Parent Processn");
printf("getpid is %dn",getpid());
printf("getppid is %dn",getppid());
}
}
Output:
[cse@server2~]$ cc syscall5.c
[cse@server2~]$ ./a.out
Child Process
getpid is 8862
getppid is 8861
Parent Process
getpid is 8861
getppid is 8617
f. fork() & wait( )
Source Code:
77. 75
pid1=fork();
if(pid1==0)
printf("2nd Child %dn",getpid());
else
{
cpid=wait(0);
printf("Child with cpid %d Died n",cpid);
cpid=wait(0);
printf("Child with cpid %d Died n ",cpid);
}
}
}
Output:
[cse@server2~]$ cc syscall7.c
[cse@server2~]$ ./a.out
1stChild 8903
Child with cpid 8903 Died
2nd Child 8904
Child with cpid 8904 Died
h. opendir() , readdir() & closedir()
Source Code:
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
main(int argc,char *argv[])
{
DIR *dir;
struct dirent *rddir;
dir=opendir(argv[1]);
while((rddir=readdir(dir))!=NULL)
{
if(strcmp(rddir->d_name,argv[2])==0)
{
closedir(dir);
printf("The File %s is Found in %sn",argv[2],argv[1]);
exit(0);
}
}
printf("The File %s could not be Found in %sn",argv[2],argv[1]);
78. 76
closedir(dir);
}
Output:
[cse@server2~]$ cc syscall12.c
[cse@server2~]$ ./a.out cse sample
The File sample is Found in cse
3.2. Implementation of C program using the following I/O system calls of UNIX operating
system open (), close (), read (), write ()
a. Making the child to perform write and the parent to read
Source Code:
#include<stdio.h>
#include<fctnl.h>
main()
{
int fp,pid;
char chr='A';
pid=fork();
if(pid==0)
{
fp=open("file",O_WRONLY,0666);
printf("In Child: character %cn",chr);
chr='B';
write(fp,&chr,1);
printf("In Child: character After Writing %cn",chr);
close(fp);
}
else
{
wait(0);
fp=open("file",O_RDONLY);
read(fp,&chr,1);
printf("ln Parent: character is ---%cn",chr);
close(fp);
}
}
Output:
[cse@server2~]$ cc iosyscall1.c
79. 77
[cse@server2~]$ ./a.out
In Child: character A
In Child: character After Writing B
In Parent: character is ---A
b. To read the characters from a file
Source Code:
#include<stdio.h>
#include<fcntl.h>
main()
{
char buff[11];
int pid;
int fp;
fp=open("file",O_RDONLY);
pid=fork();
if(pid==0)
{
printf("Child Begins %dn",getpid());
read(fp,buff,10);
buff[10]='0';
printf("Child Reads n",puts(buff));
printf("Child Exitsn");
}
else
{
read(fp,buff,10);
buff[10]='0';
printf("Parent Reads n",puts(buff));
printf("Parent Exitsn");
}
}
Output:
[cse@server2~]$ cc yuvio2.c
[cse@server2~]$ ./a.out
Child Begins 1883
firstname
Parent Reads
Parent Exits
[tit059@localhost tit059]$ firstname
Child Reads
80. 78
Child Exits
c. To move the file pointer using lseek()
Source Code:
#include<fcntl.h>
main()
{
int fp;
int pid;
char buff[11];
fp=open("file",O_RDONLY);
pid=fork();
if(pid==0)
{
printf("File Handle is %dn",lseek(fp,01,1));
read(fp,buff,10);
buff[10]='0';
printf("File Handle is %dn",lseek(fp,01,1));
}
else
{
wait(0);
printf("File Handle is %dn",lseek(fp,01,1));
}
close(fp);
}
Output:
[cse@server2~]$ cc yuvio3.c
[cse@server2~]$ ./a.out
File Handle is 1
File Handle is 12
File Handle is 13
SIMULATION OF UNIX COMMAND
4. Implementation of C program to simulate UNIX command - LS
Source Code:
#include<stdio.h>
#include<dirent.h>
81. 79
main(int argc,char *argv[])
{
DIR *d;
struct dirent *r;
d=opendir(argv[1]);
while((r=readdir(d))!=NULL)
{
printf("%sn",r->d_name);
}
}
Output:
[cse@server2~]$ cc lssample.c
[cse@server2~]$ ./a.out lssample
.
..
ram
raj
CPU SCHEDULING ALGORITHM
5.1. Implementation of first come first serve scheduling
Source Code:
#include<stdio.h>
struct fcfs
{
int arrt,burstt,waitt,turnt,run,fint;
}p[10];
struct fcfs t;
int pc=0;
int main()
{
int i,j,n;
float twaitt=0.0,tturnt=0.0;
printf("Enter the Number of Processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Process %d Arrival Time(ms):",i+1);
scanf("%d",&p[i].arrt);
printf("Enter the Process %d Burst Time(ms):",i+1);
scanf("%d",&p[i].burstt);
}
83. 81
[cse@server2~]$ ./a.out
Enter the Number of Processes: 4
Enter the Process 1 Arrival Time (ms): 0
Enter the Process 1Burst Time (ms): 3
Enter the Process 2Arrival Time (ms): 2
Enter the Process 2Burst Time (ms): 1
Enter the Process 3Arrival Time (ms): 5
Enter the Process 3Burst Time (ms): 5
Enter the Process 4 Arrival Time (ms): 6
Enter the Process 4 Burst Time (ms): 2
FCFS Scheduling:
PNo. ArrTime(ms) BurstTime(ms) WaitTime(ms) FinTime(ms) TurnTime(ms)
1 0 3 0 3 3
2 2 1 1 4 2
3 5 5 0 10 5
4 6 2 4 12 6
Average Waiting Time: 1.250000 ms
Average Turnaround Time: 4.000000 ms
5.2. Implementation of shortest job first scheduling
Source Code:
#include<stdio.h>
int sjf();
struct sjf
{
int arrt,burstt,waitt,turnt,fint;
}p[10];
int n,exe[10],rem[10];
struct sjf t;
int main()
{
int i,j;
float twaitt=0.0,tturnt=0.0;
printf("Enter the Number of Processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Arrival Time of Process %d (ms):",i+1);
scanf("%d",&p[i].arrt);
printf("Enter the Burst Time of Process %d (ms):",i+1);
scanf("%d",&p[i].burstt);
}
for(i=0;i<n;i++)
87. 85
Output:
[cse@server2~]$ cc sjf.c
[cse@server2~]$ ./a.out
Enter the Number of Processes 4
Enter the Arrival Time of Process1 (ms): 0
Enter the Burst Time of Process1 (ms): 3
Enter the Arrival Time of Process2 (ms): 5
Enter the Burst Time of Process2 (ms): 5
Enter the Arrival Time of Process3 (ms): 7
Enter the Burst Time of Process3 (ms): 10
Enter the Arrival Time of Process4 (ms): 8
Enter the Burst Time of Process4 (ms): 3
SJF Scheduling
PNo. ArrTime(ms) BurstTime(ms) WaitTime(ms) FinTime(ms) TurnTime(ms)
1 0 3 0 3 3
2 5 5 0 10 5
3 7 10 6 23 16
4 8 3 2 13 5
Average Waiting Time: 2.000000 ms
Average Turnaround Time: 7.250000 ms
5.3. Implementation of priority scheduling
Source Code:
#include<stdio.h>
int priority();
struct priort
{
int arrt,burstt,waitt,turnt,fint;
int priority;
}p[10];
int n,exe[10],rem[10];
struct priort t;
int main()
{
int i,j;
float twaitt=0.0,tturnt=0.0;
printf("Enter the Number of Processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{