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

A8517-Operating Systems Laboratory

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

A8517-Operating Systems Laboratory

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

VARDHAMAN COLLEGE OF ENGINEERING

(AUTONOMOUS)
Affiliated to JNTUH, approved by AICTE, Accredited by NAAC with A++ Grade
ISO 9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India

Laboratory Manual
Operating Systems Laboratory
(II B. Tech- II SEMESTER)
(VCE-R22)
Course Code-A8517
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VARDHAMAN COLLEGE OF ENGINEERING


(AUTONOMOUS)
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
PROGRAM OUTCOMES (POS)
PO1: Engineering Knowledge: Apply knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution complex engineering
problems.
PO2: Problem Analysis: Identify, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences.
PO3: Design/ Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet specified needs with
appropriate consideration for public health and safety, cultural, societal and environmental
considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data and
synthesis of information to provide valid conclusions.
PO5: 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.
PO6: The Engineer and Society: Apply reasoning informed by contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of professional engineering
solutions in societal and environmental contexts and demonstrate knowledge of and need
for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of engineering practice.
PO9: Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams and in multi-disciplinary settings.
PO10: 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.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of
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.
PO12: 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.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: To collect requirements, analyze, design, implement and test software Systems.
PSO2: To analyze the errors and debug them within minimal time.
COURSE OVERVIEW:
Operating Systems is a graduate-level introductory course that teaches the concepts in
operating systems like abstractions, mechanisms, and various services provided. This course
deals with Process Management & Synchronization, Inter process communication, Memory
Management, Virtual Memory, File & Disk Management and Deadlock handling methods.
Using these concepts, the student will be able to understand the internal working of various
operating systems. This course also covers commands, shell script and IPC mechanisms in
UNIX/LINUX environment. The course provides the concepts and terminology required for
advanced courses.
COURSE OBJECTIVE
The course enables the learner to apply Operating System Concepts in UNIX/LINUX/Ubuntu
Operating System.
COURSE OUTCOMES (COs)
After the completion of the course, the student will be able to:
CO# Course Outcomes
Make use of UNIX utilities and System calls for Process, Memory and File
A8517.1
Management.
A8517.2 Choose the IPC mechanism to provide communication among processes.
A8517.3 Write Shell script code to simulate UNIX commands and run own script.
A8517.4 Develop programs for handling memory and deadlocks.

BLOOM’S LEVEL OF THE COURSE OUTCOMES


Bloom’s Level
CO# Remember Understand Apply Analyze Evaluate Create
(L1) (L2) (L3) (L4) (L5) (L6)
A8517.1 ✔
A8517.2 ✔
A8517.3 ✔
A8517.4 ✔

COURSE ARTICULATION MATRIX


PO10

PO11

PO12

PSO1

PSO2

CO#/
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9

POs

A8517.1 3 2 2 2
A8517.2 3 2 2
A8517.3 3 2 2 2
A8517.4 3 2 2
Note: 1-Low, 2-Medium, 3-High
LIST OF PROGRAMS FOR PRACTICE:
Tools and
No Title of the Experiment Expected Skills/Ability
Techniques
Practice commands - like mkdir, rmdir,
1
cat,nl, ls, cp, mv, rm, man.
Practice commands - like wc, uniq,
Identify the various File
2 comm, cmp, diff, ln, unlink, chmod, du,
handling Utilities
df.
Practice commands - head, tail, sort,
3
grep, egrep, fgrep, cut, paste, join.
Process Management System calls fork Examine process
4
(), exec () and wait (). creation and execution
a) Two-way Communication using Pipes.
5 Implement IPC
b) Process Communication using FIFOs.
mechanisms using UNIX
6 Implement Shared Memory form of IPC. API
7 Implement Message Queue form of IPC. Open source
Ubuntu/Linux
Use UNIX/LINUX system
Operating
calls to simulate
8 Simulate cp, head and tail commands. System.
commands
C/C++
Compiler
Shell Script programs using control Write Shell Script
9
statements. Programs
Shell Script programs using control Write Shell Script
10
statements. Programs
Implement Page
Program to implement FIFO AND LRU
11 Replacement
Page replacement algorithms.
algorithms.
Program to implement FCFS and SSTF Implement Disk
12
Disk Scheduling algorithm. Scheduling algorithms.
Implement Process
13 Implement Semaphore form of IPC. Synchronization using
Semaphores
ASSESSMENT SCHEME R22

Max. Marks
S.NO# EVALUATION METHOD ASSESSMENT TOOL
Marks Total
A write-up on day-to-day experiment in
10
the laboratory
Viva-voce (or) tutorial (or) case study (or)
application (or) poster 10
Continuous Internal
presentation of the course
Evaluation (CIE)
1 40
Internal practical examination 10
Laboratory Project, which consists of the
Design (or) Software / Hardware Model
10
Presentation (or) App Developm (or)
Prototype Presentation
Write-up 10
Experiment/program 15
Semester End Evaluation of results 15
2 60
Examination (SEE)
Presentation on another
10
experiment/program
Viva-Voce 10
LAB SESSION PLAN

CO BLOOM’s
No Title of the Experiment
LEVEL
Practice commands - like mkdir, rmdir, cat,nl, ls, cp, CO-1 L3
1
mv, rm, man.
Practice commands - like wc, uniq, comm, cmp, diff, ln, CO-1 L3
2
unlink, chmod, du, df.
Practice commands - head, tail, sort, grep, egrep, CO-1 L3
3
fgrep, cut, paste, join.
Process Management System calls fork (), exec () and CO-2 L3
4
wait ().
a) Two-way Communication using Pipes. CO-2 L3
5
b) Process Communication using FIFOs.
6 Implement Shared Memory form of IPC. CO-2 L3
7 Implement Message Queue form of IPC. CO-2 L3
8 Simulate cp, head and tail commands. CO-3 L3
9 Shell Script programs using control statements. CO-3 L3
10 Shell Script programs using control statements. CO-3 L3
Program to implement FIFO AND LRU Page CO-4 L3
11
replacement algorithms.
Program to implement FCFS and SSTF Disk Scheduling CO-4 L3
12
algorithm.
13 Implement Semaphore form of IPC. CO-2 L3
Introduction to UNIX
What is UNIX?

 UNIX is a family of multitasking, multiuser computer operating systems that derive


from the original AT&T Unix.
 Development started in 1969 at the Bell Labs research center by Ken Thompson,
Dennis Ritchie, and others.
o It is a stable, multi-user, multi-tasking system for servers, desktops and
laptops.
o Proprietary UNIX operating systems (and Unix-like variants) run on a wide
variety of digital architectures, and are commonly used on Web servers,
mainframes, and supercomputers.
o In recent years, smart phones, tablets, and personal computers running
versions or variants of UNIX have become increasingly popular.
o UNIX is a Console User Interface (CUI) Operating System.
o UNIX is Completely written in C Language.

Different Flavors / Variants of UNIX / Types of UNIX

There are many different versions of UNIX, although they share common similarities.
1. BSD (Berkeley Software Distribution) UNIX
2. SUN SOLARIS (Sun Microsystems) [Servers & Work Stations]
3. NOVELL NETWARE (Novell)
4. IBM AIX (International Business Machines)
5. HP – UX (Hewllet Packard)
6. TRU 64 (Hewllet Packard)
7. MacOS X
8. GNU/Linux
9. Fedora Linux [servers and desktop PCs]

The UNIX Architecture


UNIX Operating System Uses Layered Architecture.
The UNIX operating environment is organized into three layers.
1. The innermost level of UNIX is the kernel. This is the actual operating system, a
single large program that always resides in memory. Sections of the code in this
program are executed on behalf of users to do needed tasks. Like access files or
terminals. Strictly speaking, the kernel is UNIX.
 Kernel − the kernel is the heart of the operating system.
 Kernel - interacts with the hardware directly.
 User Communicate with kernel with System calls
 Kernel Performs the functions Like
o File Management
o Controls Computer Hardware Resources memory, CPU and I/O.
o Memory Management
o Scheduling CPU Time between Processes
o Managing Data Transfer between Files and H/W
o Handling Interrupts
o Controls the Hardware resources
o Controls the access to computer by Several Users
2. The next level of the UNIX environment is composed of Programs, Commands or
Utilities.
Commands and utilities of UNIX are simply a set of programs that have become
standardized and distributed.
This level also includes standardized system routines, or application programming
interfaces (APIs), that programmers can use to create new programs and utilities.
3. The final level of the Unix environment, which stands like an umbrella over the
others, is the shell.
The shell processes your terminal input and starts up the programs that you
request. i.e. The Shell is the utility that processes user requests.
 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 for them to be carried out.
 The commands or utilities are themselves programs.
Files and Processes
Everything in UNIX is either a File or a Process.
UNIX Processes
 A Process is an instance of a program, with its needed environment of file
connections, etc., running in the CPU.
 In UNIX, every command or program you run becomes a separate process.
 Processes can also be combined in interesting ways to do complicated tasks.
 A process is an executing program identified by a unique PID (process
identifier).
A UNIX File:
 A File is a collection of data. They are created by users using text editors,
running compilers etc.
 Examples of files:
 a document
 the text of a program written in some high-level programming language
 instructions comprehensible directly to the machine (an executable or binary
file)
 A directory, containing information about its contents, which may be a
mixture of other directories (subdirectories) and ordinary files.

Advantages of UNIX
 Full multitasking with protected memory. Multiple users can run multiple
programs each at the same time without interfering with each other or crashing
the system.i.e. Multi User and Multi-Tasking System.
 Most of UNIX flavors are Open Source. (Freeware)
 UNIX is Extensible and Scalable Operating System.
 Very efficient virtual memory, so many programs can run with a modest
amount of physical memory.
 Access controls and security.
 A rich set of small commands and utilities that do specific tasks
 Ability to string (combine) commands and utilities together in unlimited ways
to accomplish more complicated tasks .
 A powerfully unified file system. Everything is a file: data, programs, all
physical devices and Directories.
 A lean kernel that directly communicate with Hardware.
 Available on a wide variety of machines - the most truly portable operating
system.

Disadvantages of UNIX
 The traditional command line shell interface is user hostile -- designed for the
programmer, not for the casual user.
 Commands often have cryptic names and give very little response to tell the
user what they are doing. Much use of special keyboard characters.
 To use UNIX well, you need to understand some of the main design features. Its
power comes from knowing how to make commands and programs interact
with each other.
 Richness of utilities (over 400 standard ones) often overwhelms novices.
Documentation is short on examples and tutorials to help you figure out how
to use the many tools provided to accomplish various kinds of tasks.
UNIX BASIC COMMANDS

A Utility or Command is a standard UNIX/LINUX program (process) that provides a support


process for users.
The various utilities can be
1. File Handling Utilities
2. Process Utilities
3. Text Processing Utilities
4. Backup Utilities
5. Filters
6. Disk utilities
7. Networking Commands …

Command Syntax in UNIX

$verb [options] [arguments]


Eg: wc –lc file1 file2
Verb: Command Name, Tells what action to be done.
Eg: wc
Options: Modifies how the action is applied, options are specified using +/-
and many options can be specified at a time.
Eg: -lc
Arguments: Provides additional information to the command. (File names,
device name etc).
Eg: file1, file2

S.No Command Name and Syntax Options and Example


1 1. date command
-s : To set the date
Display the system date and time.
-u : To display Universal Time
$ date -s "Sun Dec 18 21:00:00 PDT 2016" +%a or +%A : To display Weekday name +%b or
$ date -u +%B :To display Month name
$ date +%a +%d: To display current day of month
$ date +%B +%D: To display current date in mm/dd/yy
$ date +%d +%F: To display date in YYYY-MM-DD
$ date +%D +%T: To display time in 24 hours format
$ date +%F hh:mm:ss
$ date +%T

2 2. cal command –y: displays complete year calendar.


 Displays the calendar for a specific $cal
month or for a year
$cal 12 2017
 It uses arguments.
 If arguments are not specified it $cal –y 2017
displays the current month calendar.
$cal 2017
 If single argument with 4 digits will
display whole year calendar (1-9999)
 If two arguments are specified,
denotes month and year.
3 echo command -n: Do not output a trailing newline.
-e: Enable interpretation of backslash escape
 Displays a line of text. i.e. It copies its
sequences
arguments back to the terminal.
\\ A literal backslash character ("\").
$ echo -e 'Hello \bworld \bhow \bare \byou \a An alert (The BELL character).
.'
$ echo -e 'Hello \nworld \nhow \nare \b Backspace
\nyou.'
\n A newline.
$ echo -e 'Hello \tworld \thow \tare \tyou ‘
$ echo -e 'Hello \vworld \vhow \vare \vyou ‘ \t A horizontal tab.
\v A vertical tab.
$echo Hello World
$echo “Hello World”
4 clear command
 clear the terminal screen, puts the
cursor at the top of the screen $clear
5 script command -a: Append the output to file or typescript,
retaining the prior contents.
 Used to record an interactive
$script MyFile
session.
$date
 If the argument file is given, script
$cal
saves all dialogue in file. If no file
$echo ‘hello’
name is given, the typescript is saved
$exit
in the file typescript.
$script MyFile
-To Use the previous script
$script –a MyFile
$cal
$echo ‘hello’
$exit
6 uname command -a: print all information
-s: print the kernel name
 displays about the user (system
-n: print the network node hostname
information). -r: print the kernel release
-I: print the hardware platform
$uname
$uname –a
7 passwd command
$ passwd
 Used to change the user Password
(current) UNIX password:
 The passwd command changes Enter new UNIX password:
passwords for user accounts. A Retype new UNIX password:
normal user may only change the
password for his/her own account, passwd: password updated successfully
while the superuser may change the
password for any account.
Practice commands – mkdir, rmdir, cat,nl, ls, cp, mv,
Week-1
rm, man.

1. What is an Operating System?


2. List the services provided by the Operating System?
Pre-Lab 3. How do we use services provided by the Operating System?
Questions 4. What are the characteristics to evolve the different Operating Systems?
5. Identify the names of different operating systems.

S.No Command Name and Syntax Options and Example


1 mkdir (Make Directory) –m: to specify the directory
 mkdir command in Linux allows the permissions.
user to create directories (folders in –p: to create sub directories.
some operating systems ). $ mkdir mydir
 This command can create multiple $ mkdir -m a=rwx mydir
directories at once. //Create the mydir directory, and set its
 set the permissions for the permissions such that all users may read,
directories. write, and execute the contents.
 If the permissions are not specified, $ mkdir Mydir1 Mydir2 Mydir3
the directory typically will have read
$ mkdir –p /home/ Mydir1 Mydir2
and execute permissions to all 3
types of users and write only for $ mkdir -p first/second/third
owners.
2 rmdir (Remove Directory) $ rmdir dir1
 rmdir command is used remove
$ rmdir mydir1 mydir2 mydir3
empty directories from the
filesystem in Linux. $ rmdir -p mydir/mydir1
 So if the specified directory has some
directories or files in it then this
cannot be removed by rmdir
command.
 This removes only an empty
directory. i.e directory without any
sub-directories or files:
3 cat (Concatenate) -b: starting at 1, display the line number for
 Used to create simple files. non-blank output lines
 To display the text files -e: display control and non-printing chars
 To copy the contents of one file to followed by a $symbol at
another the end of each line
 To append the content to an existing -n: starting at 1, number all output lines.
file $cat > myFile1
The operators used are ……… // creating file
>: Redirect the output of the cat command cntrl + d
to a file rather than standard output. $cat myfile1 myfile2
(Monitor) //display the contents of files
>>: Append the output of cat command to $cat myfile1 > myfile3
the end of an existing file. //copy contents from one file to another
$cat >> myfile1
…….. //Appending to a file
$cat –b myfile1
$cat –n myfile1
4 nl (Number Lines) -s: to specify the delimiter (by default the
 used to prefix line number for each delimiter is white space)
line in one or more files. -w: to specify the width of number format
 Numbers all non-empty lines. -i: line number increment at each line
 If no file name specified, the $ nl myfile.txt
command read from keyboard. $ nl –a myfile.txt
$nl –b “cse” myfile.txt
$ nl -i 3 geekfile.txt
$ nl –w3 myfile.txt
$ nl –w3 -s: myfile.txt

5 ls (lists) -l: display long list of working directory or


is a Linux shell command that lists specified directory name.
directory contents of files and directories. -a: display all the files including hidden files also
The contents of long list includes -1: display all in one column
1. File Type -r: display in descending order of files
- : regular file -R: display recursive list. i.e. Sub directories also.
d : directory file -i: displays i-Node number of a file.
b : block file -t: It sorts the file by modification time,
l : link file showing the last edited file first.
2. File Permission $ls
3. Number of links $ls –l mydir
4. User Name $ls –l
5. Group Name $ls –a
6. File Size $ls -1
7. Last Modified data & Time $ls –r
8. File Name $ls –i myfile
$ls –R myfile

6 cp (Copy) -v : (verobose) – to see the files are copied.


 This command is used to copy files or -p : (preserve) – If destination file exists, the
group of files or directory. source file attributes are preserved.
 It creates an exact image of a file on -i : (Interactive)- If destination file exists, its
a disk with different file name. contents are removed after taking user
 cp command require at least two confirmation.
filenames in its arguments. -R or –r (Recursive)- Copies all directories, sub
 If destination file already exists, its directories and their files.
contents are replaced with source -b(backup): With this option cp command
file. creates the backup of the destination file in the
 It copies both text and binary files. same folder with the different name and in
 After copy , the permissions of the different format.
file are preserved. cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3
Source-n Directory
cp -R Src_directory Dest_directory
$ cp -b a.txt b.txt
$ cp *.txt Folder1 //wild card copy
7 mv (move) -i : Interactive
mv is used to move one or more files or -f : forced deletion
directories from one place to another. -u: move only files that are not in destination.
After move, old file will be lost and new file -b(backup):
is found at destination.
It has two distinct functions: mv [Option] source destination
(i) It rename a file or folder. $ mv a.txt geek.txt
(ii) It moves group of files to different $ mv -i geek.txt b.txt
directory. $mv dir1 dir2
No additional space is consumed on a disk $mv –u dir1 dir2
during renaming. $mv my* dir1
8 rm (remove) -f : forced removal
rm command is used to remove objects such -i: interactive, ask the user for confirmation
as files, symbolic links and so on.It is used to before remove.
remove a file entry from the directory. rm [OPTION]... FILE...
It cannot be used to remove directory. $ rm b.txt c.txt
$ rm -i d.txt
$ rm –f d.txt

9 man (manual)
Used to display the user manual of any -k : Displays the related commands.
command that we can run on the terminal.
It is used to obtain offline documentation of $man [OPTION]... [COMMAND NAME]...
any command. $ man printf
It provides a detailed view of the command $man cat
which includes name, synopsis, description, $man –k sort
options, exit status, return values, errors,
files, versions, examples, authors and see
also.
If no options, It displays the whole manual
of the command.

1. How do we create simple files in UNIX?


2. Describe the various field in Command Syntax?
3. Can a command use more than one option? Show with an example.
4. How UNIX provides to know the command description.
5. Can we remove a directory using rm command?
6. What do we need to follow when using rmdir command?
7. Can we rename a file using mv command? Give example for it.
Post-Lab 8. List any four options in using cp command.
Questions 9. Is mkdir allows to give permissions to a directory? If so give an example for
it.
10. Write the syntax and options for nl command.
11. Is the cat command allowing to append content to a file?
12. Give the process how to concatenate two files using cat command.
13. How to know the properties of a file and directory using ls command?
14. In UNIX what kind of permissions are set for files and directories?
15. In UNIX what kind of users exist in working with system.
Practice commands wc, uniq, du, df , chmod ,comm,
Week-2
cmp, diff, ln, unlink.

1. What is the dual mode operation of Operating System?


2. How to number lines using UNIX command?
3. Write the syntax to perform various operations with cat command.
Pre-Lab 4. What is degree of multi programming?
Questions 5. How do you compare cp and mv command?
6. Can we give more than one argument to a command? If so give an
example for it.

S.No Command Name and Syntax Options and Example


1 wc command (word count) $wc [OPTION]... [FILE]...
 It is used to find out number of
lines, word count, byte and $wc myfile1
characters count in the files specified $wc myfile1 myfile2
in the file arguments.
 The character count includes new The options are
lines also -l: This option prints the number of lines present in
 By default it displays four-columnar a file.
output. $wc –l myfile1
 First column shows number of lines $wc –l myfile1 myfile2
present in a file specified, second
column shows number of words -w: This option prints the number of words present
present in the file, third column in a file.
shows number of characters present
in file and fourth column itself is the $wc –w myfile1
file name which are given as $wc –w myfile1 myfile2
argument. -c: This option displays count of bytes/characters
 When more than file name is present in a file
specified in argument then command $wc –c myfile1
will display four-columnar output for $wc –c myfile1 myfile2
all individual files plus one extra row -L: it can be used to print out the length of longest
displaying total number of lines, (number of characters) line in a file.
words and characters of all the files $wc –L myfile1
specified in argument, followed by To count all files and folders in a file
keyword total. $ls ramesh | wc -l
2. uniq command $uniq myfile1
 Reports or filters out the repeated The options are
lines in a file. -c: It tells the number of times a line was
 Locates repeated and non repeated.(count)
repeated lines. $uniq –c myfile
 Deletes the duplicate lines,
keeping the first and deleting the
others. -d: It only prints the repeated lines only once.
 To delete, the lines must be (duplicate)
adjacent.
 uniq is the tool that helps to $uniq –d myfile1
detect the adjacent duplicate lines
and also deletes the duplicate -D: It displays all occurrences of the repeated
lines. lines(duplicate)
 uniq filters out the adjacent $uniq –D myfile1
matching lines from the input
file(that is required as an -u: It prints only the unique lines.
argument) and writes the filtered $uniq –u myfile1
data to the output file
-w: limit the comparison to a set number of
characters.
Eg: Wel Done
Wel Come
Wel Going

$uniq –w 3 myfile1 //Wel

-i: It is used to make the comparison case-


insensitive.
$uniq –i myfile1
If lines are not adjacent, they must be sorted
before the uniq command.
Eg: $sort myfile1 | uniq
3 du command (disk usage) du /ramesh/cse
 Summarize the disk usage of the
set of files, recursively for The options are
directories. -h: print sizes in human readable format
 Used to estimate file space usage. -a: printing all files including directories.
 Used to track the files and -c: to print grand total.
directories which are consuming -s: summary of file system
excessive amount of space on du –s /vce/cse
hard disk drive.
4 df command (disk free) $df
 Reports the file system disk space $df myfile1
usage.
 df displays the amount of disk The options are
space available on the file system -a: It includes all the dummy files also in the output
containing each file argument. which are actually having zero block sizes.
 If no file name is given, the space $df –a
available on all the currently
mounted file system is shown. -h: It prints sizes in human readable format.
 By default, df shows the disk
space in 1 K blocks. $df –h

-i: to display the inode information instead of


block usage.
5 chmod command (change mode) The permissions can be changed in three ways
 Used to change the access mode of 1. Relative permissions
a file. Eg: Adding writes permissions to user and execute
 Changing file permissions permissions to all.
 The chmod command is used to set $chmod u+w,ugo+x myfile1
the permissions of one or more $chmod u+w,a+x myfile1 myfile2
files. $chmod u+w, +x myfile1
 A File or Directory is created with a Eg: Removing Write permissions to others
default set of permissions. $chmod o-w myfile1 myfile2
Eg: Remove Execute permissions to group and add
UNIX/LINUX provides three types of write to others.
permissions to a file or directory. $chmod g-x,o+w Myfile1
read – r
write – w Eg:$chmod u+rwx myfile1
execute – x $chmod a+rwx myfile1
The three permissions are given to three
types of users Note: Using relative permissions the other
User(owner) – u permissions are unchanged.
Group - g
Others - o 2. Absolute permissions
Using absolute permissions, all permissions are
[ALL : a -> ugo] unchanged.

$chmod –options mode file/dir 3. Using Octal Codes


Eg: $chmod 764 myfile1
Mode => Specified as
MODE
who operator permissions
(u,g,o,a)+,-,= r,w,x

6 cmp command (Compare) $cmp myfile1 myfile2


 The two files are compared byte by The options are
byte; the location of the first -l: Displays all the differences found in files byte by
mismatch is shown on the screen. byte.
 Helps to find out whether the two
files are identical or not. $cmp –l myfile1 myfile2
 When cmp is used for comparison
between two files, it reports the -s: suppress list option, no output is displayed. This
location of the first mismatch to gives an exit value of 0 if the files are identical, a
the screen if difference is found. value of 1 if different, or a value of 2 if an error
 cmp displays no message and message occurs.
simply returns the prompt if the $cmp –s myfile1 myfile2
the files compared are identical.
-b: displays the differing bytes in the output.
$cmp –b myfile1 myfile2

-i: skip a particular number of initial bytes from


both the files.
$cmp –i 10 myfile1 myfile2
-n: limit the number of bytes you want to compare
$cmp –n 10 myfile1 myfile2
7 comm command (common) $comm myfile1 myfile2
Compare two sorted files line by line and The options are
write to standard output; the lines that are -1: suppress first column
common and the lines that are unique. -2: suppress second column
It compares the files line by line and -3: suppress third column
displays the result in 3 columns. $comm -1 myfile1 myfile2
Col1 : Unique lines in file1 $comm -2 myfile1 myfile2
Col2: Unique lines in file2 $comm -3 myfile1 myfile2
Col3: Common lines in both the files. $comm -12 myfile1 myfile2
$comm -23 myfile1 myfile2
8 diff command (difference) $diff myfile1 myfile2
 Used to display the differences in
the files by comparing the files line The options are
by line.It tells us which lines in one -b : Ignore Trailing Blanks
file have is to be changed to make -w : Ignore White space
the two files identical.When used -i : Ignore the case in comparison
with same files, it produces a
detailed output. $diff –i myfile1 myfile2

In Output
c – Change, d – Delete, a- Append

9 ln command (link command)


A file is linked with ln command. The  If a file is shared by two or more users,
command will take two arguments. The ln instead of providing same copy a link is
command is used to create links between created for the file in each user.
files. Unix/Linux allows two types of links.
1. Hard Links Hardlink
The default link type is hard link. ln myfile1 mylink1
Ln command executed with no options is a ln myfile1 mylink2
hard link. ln myfile1 mylink3 mylink4
Hard links must be made within the file
system only. ln mydir link1 -> invalid
Hard links are created only for regular files
but not to directories. ln /home/vce/myfile /user/ramesh/mylink
Hard links refer to specific location of (invalid)
physical data.
After each link to a file, the hard link count -i: used to see the inode number.
is incremented by 1. ln –i myfile1 mylink3 mylink4
Hard links are most useful for keeping file Note: I-Node number of links and file will be same.
content in a single location by avoiding Symbolic link
duplication of what might be a very large ln –s myfile1 link1
amount of data. ln –s mydir mylink
2. Symbolic links
 Allows creating a link to a ln /home/vce/myfile /user/ramesh/mylink
directory, to a different file system
or in different partitions. A
symbolic link also known as a
softlink or symlink.
 It is a special file link to a file or
directory.ln command with –s is
used to create symbolic links.
10 unlink command $unlink mylink1
Used to remove a link from the file $unlink mylink2 mylink3
system.After each unlink, the hard link  It is similar to rm command
count is decremented by 1. $rm mylink
1. How to know the number of characters in a file?
2. How the uniq command identifies repeated lines in a file?
3. List the commands to compare files using unix.
4. When the cmp command terminates from its execution?
5. If two files are identical, what is the output of the cmp command?
6. Is it required to sort files before applying comm command?
7. How do you see the output after comm command execution on two sorted
Post-Lab files?
Questions 8. How the diff command differs from other file comparison commands?
9. What suggestions a diff command gives when executing with two files?
10. What is the need of ln command in Unix?
11. Is link also a file? If so, what are the options to remove a link in unix
environment.
12. How do you distinguish between absolute and relative permissions?
13. Is it required to change the permissions of every file?
Practice commands - head, tail, sort, grep, egrep,
Week-3
fgrep, cut, paste, join.

1. During context switch of a process, operating system stores the current


state of the process in which data structure?
2. How would you differentiate pre-emptive and non-pre-emptive
scheduling algorithms?
3. Dow do we compare two files character by character.
4. Write the complete command for the following context.
From two sorted files of employees eating habits, display the employees
Pre-Lab list who take both veg and nonveg.
Questions 5. Write the complete command to change the file permissions as below.
“Add write, execute permissions to group and remove write permissions
to others”.
“Change all the permissions such that all users only have read and write
permissions.”
6. Write a command to list the number of files and directories in working
directory.

S.No Command Name and Syntax Options and Example


1 head command The options are
The head command, as the name implies, -n num: Prints the first ‘num’ lines instead of
print the top N lines number of data of first 10 lines
the given input. $head -n 5 myfile1 myfile2
By default, it prints the first 10 lines of $head -4 myfile1 myfile2
the specified files.
If more than one file name is provided, -c num: Prints the first ‘num’ bytes from the file
then data from each file is preceded by specified. Newline count as a single character,
its file name. so if head prints out a newline, it will count it as
Displays the beginning of one or more a byte.
files $head -c 5 myfile1 myfile2

head myfile1 //displays top 10 lines -q: It is used if more than 1 file is given. Because
head myfile1 myfile2 of this command, data from each file is not
//displays top 10 lines from both the files proceeds by its file name.
$head -4 myfile1 //display top 4 lines $head -q –n 5 myfile1 myfile2

-v: By using this option, data from the specified


file is always preceded by its file name.
$head –v myfile1.

2. tail command The options are


The tail command, as the name implies, -n num: Prints the last ‘num’ lines instead of last
print the last N number of data of the 10 lines.
given input. $ tail -n 3 myfile1 myfile2
By default it prints the last 10 lines of the $ tail -3 myfile1
specified files. Tail command also comes with an ‘+’ option
If more than one file name is provided which is not present in the head command. With
then data from each file is precedes by its this option tail command prints the data starting
file name. from specified line number of the file instead of
Displays the end of the one or more files. end.
$ tail +5 myfile1
$tail myfile1 //displays last 10 lines
$tail myfile1 myfile2 -c num: Prints the last ‘num’ bytes from the file
//displays last 10 lines from both the files specified. Newline count as a single character,
$tail -4 myfile1 //display last 4 lines so if tail prints out a newline, it will count it as a
byte.
$ tail -n 7 state.txt | sort –r $ tail -c -6 myfile1
$ tail -c 6 myfile1
By +num, it display all the data after
$ cat state.txt | head -n 20 | tail -n 5 > skipping num bytes from starting of the
list.txt specified file and by -num, it display the
last num bytes from the file specified.
$ tail -c +5 myfile1
$ head -n 20 state.txt | tail -10
-q: It is used if more than 1 file is given. Because
of this command, data from each file is not
precedes by its file name.
$ ls -t | head -n 3 | sort
$ tail –q state.txt capital.txt
-v: By using this option, data from the specified
file is always preceded by its file name.
$ tail –v state.txt capital.txt

3 sort command $ sort filename.txt


SORT command is used to sort a file,
The options are
arranging the records in a particular
order. By default, the sort command
-r Option: Sorting In Reverse Order: You can
sorts file assuming the contents are
perform a reverse-order sort using the -r flag.
ASCII. Using options in sort command, it
the -r flag is an option of the sort command
can also be used to sort numerically.
which sorts the input file in reverse order i.e.
 SORT command sorts the contents of descending order by default.
a text file, line by line. $ sort -r inputfile.txt
 The sort command can also sort by
-n Option: To sort a file numerically
items not at the beginning of the line
// the file with numeric data
 Sorting is done based on one or more
$ sort -n filename.txt
sort keys extracted from each line of
$ sort -nr filename.txt
input.
 By default, the entire input is taken as
-k Option: Unix provides the feature of sorting a
sort key. Blank space is the default
table on the basis of any column number by
field separator
using -k option.
For example, use “-k 2” to sort on the second
The sort command follows these features
column.
as stated below:
$sort –k 2 emp.txt
1. Lines starting with a number will
//sort by second field.
appear before lines starting with a
-c option: This option is used to check if the file
letter.
given is already sorted or not & checks if a file is
2. Lines starting with a letter that
already sorted pass the -c option to sort.
appears earlier in the alphabet will
$ sort -c filename.txt
appear before lines starting with a
-u option: To sort and remove duplicates pass
letter that appears later in the
alphabet. the -u option to sort.
3. Lines starting with a lowercase letter $ sort -u filename.txt
will appear before lines starting with -M Option: To sort by month pass the -M option
the same letter in uppercase. to sort. This will write a sorted list to standard
output ordered by month name.
$ sort –M months.txt
4 cut command The Options are
The cut command in UNIX is a command -b(byte): To extract the specific bytes, you need
for cutting out the sections from each to follow -b option with the list of byte numbers
line of files and writing the result to separated by comma. Range of bytes can also be
standard output. specified using the hyphen(-). Tabs and
It can be used to cut parts of a line backspaces are treated like as a character of 1
by byte position, character and field. byte.
Basically the cut command slices a line $ cut -b 1,2,3 myfile
and extracts the text. $ cut -b 1-3,5-7 myfile
$ cut -b 1- myfile
$ cut -b -3 myfile
$ cat state.txt | cut -d ' ' -f 1 | sort –r -c (column): To cut by character use the -c
option. This selects the characters given to the -
$ cat state.txt | head -n 3 | cut –d ' c option.
' -f 1 > list.txt $ cut -c 2,5,7 myfile
$ cut -c 1-7 myfile
$ cut -c 1- myfile
$ cut -c -5 myfile
-f (field): To extract the useful information you
need to cut by fields rather than columns. List of
the fields number specified must be separated
by comma.
$ cut -f 2 myfile
$ cut -f 2 myfile1 myfile2
-d option is used then it considered space as a
field separator or delimiter:
$ cut -d " " -f 2 myfile
$ cut -d ":" -f 2 myfile
$ cut -d " " -f 2-4 myfile
5 paste command $ paste file1 file2 file3
It is used to join files horizontally The Options are
(parallel merging) by outputting lines -d (delimiter): Paste command uses the tab
consisting of lines from each file delimiter by default for merging the files. The
specified, separated by tab as delimiter, delimiter can be changed to any other character
to the standard output. by using the -d option.
$ paste -d "|" file1 file2
-s (serial): We can merge the files in sequentially
manner using the -s option. It reads all the lines
from a single file and merges all these lines into
a single line with each line separated by tab. And
these single lines are separated by newline.
$ paste -s file1 file2

$ paste –s –d “:” file1 file2


6 join command $join file1 file2

 The join command in UNIX is a $join file1 file2 > file3


command line utility for joining
lines of two files on a common The options are
field. using -i option: join command is by default case
 Suppose you have two files and sensitive. i.e The common field is must be of
there is a need to combine these same case. If not –i is used.
two files in a way that the output $join –i file1 file2 > file3
makes even more sense. -t option: Most of the times, files contain some
 For example, there could be a file delimiter to separate the columns.
containing names and the other
containing ID’s and the
requirement is to combine both
files in such a way that the names
and corresponding ID’s appear in
the same line.
 join command is used to join the
two files based on a key field
present in both the files.

7 grep command The options are


-c: This prints only a count of the lines that
“Global Regular Expression Print”. match a pattern
The grep filter searches a file for a -h: Display the matched lines, but do not display
particular pattern of characters, and the filenames.
displays all lines that contain that -i: Ignores, case for matching
pattern. The pattern that is searched in -l: Displays list of a filenames only.
the file is referred to as the regular -n: Display the matched lines and their line
expression numbers.
Pattern can be in single or double quotes. -v: This prints out all the lines that do not
grep [options] pattern [files] matches the pattern
$grep “cse” myfile1 -o: Display only the matched pattern
-f: to keep the patterns in a file
Regular Expressions -A n: Prints searched line and nlines after the
---------------------------- result.
grep “li*” myfile* -B n: Prints searched line and n line before the
result.
*: zero or any number of -C n: Prints searched line and n lines after before
occurrences the result.
+: one or any number of $grep -i "vce" file1 file2
occurrences $grep -c "vce" file1
? : zero or one occurrence $grep -l "vce" f1.txt f2.txt f3.xt f4.txt
^: beginning of line $ grep -o "vce" myfile1
$: end of line $ grep -n "vce" myfile1
. : any character match $ grep -v "vce" myfile1
[pqr]: any one char $ grep "^vce" myfile1
[4-8]: range of chars $ grep "vce$" myfile1.txt
(Wildcard characters) $grep –f patrn.txt myfile1
8 egrep command (extended) egrep ‘patern1 | pattern2 | pattern3’ myfile1
egrep is a pattern searching command
which belongs to the family of grep //to search for multiple patterns
functions.
It treats the pattern as an extended egrep –i ‘patern1 | pattern2 | pattern3’ myfile1
regular expression and prints out the lines
that match the pattern. //ignores the case while searching the pattern
If there are several files with the matching
pattern, it also displays the file names for Note: All the options and regular expressions of
each line. “grep” can also be applied.
it is faster than the grep command.

9 fgrep command (fast) $fgrep "linux" myfile1


The fgrep filter is used to search for the
fixed-character strings in a file. There can Note: All the options and regular expressions of
be multiple files also to be searched. “grep” can also be applied.
It cannot perform search based on regular
expressions.
Displays all lines that contain that
pattern.
It is the fastest approach as no
substitution of regular expressions.

1. grep stands for ……………………………


2. Is the cut command can extract columns as characters also? Write an example
for it.
3. Join command is combining two files based on …………………
Post-Lab
4. Write the command to display the contents of a file which ends with “good
Questions day”.
5. Write the command to contents of a file which have no “the” word.
6. How do we match for patterns in a file in UNIX?
Process Management System calls fork (), exec () and
Week-4
wait () system calls.

1. How to display first 6 files or directories in the working directory.


2. Display the lines of a C program which is not ending with ;
Pre-Lab
3. Extract the department name and salary of employees in a employee file.
Questions 4. How to differentiate grep,egrep and fgrep.
5. “fgrep is faster than grep.” Justify the statement.
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
void main()
{
int pid;

pid= fork(); //fork a child process (create)

if(pid < 0)
{
printf("\n Fork failed to create a child \n");
return 1;
}
else if(pid > 0) // Parent process
{
printf("\n The parent process id is %d \n" , getpid());
printf("\n Parent Process Running \n");
wait(NULL); //Parent waits for child to complete
printf("\n Child Completed \n");
}
else
{
printf(" \n Child Process running \n");
printf("\n The child process id is %d",getpid());
printf("\n The parent of child is %d" , getppid());
execlp("/bin/ls" ,"ls", “-l” ,NULL);
}
return 0;
}

1. What are the header files required to use unix process system calls?
2. The wait () system call gets status from …………………
3. getppid() returns the process id of invoking ………………………process.
Post-Lab
4. What happens when we invoke fork () system call?
Questions 5. Is it possible to assign a new task to child process? If so, demonstrate with an
example.
6. How to create a child process in UNIX?
a) Two-way Communication using Pipes.
Week-5
b) Process Communication using FIFOs.

1. If a process calls fork() system call n-times. How many child processes are
created.?
2. If a process calls fork() system call 4 times. How many total number of processes
Pre-Lab
concurrently executed in the system?
Questions 3. Does exec() call can be made in parent process? If so, what is the need of it.
4. What is the return value of fork() system call in parent and child process?
5. When a process is terminated from the system?

a) Two-way Communication using Pipes.


#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
void main()
{
int n,p1fd[2],p2fd[2];
pid_t pid;
char msg[100];
if(pipe(p1fd)==-1) {
printf("pipe failed\n");
return;
}

if(pipe(p2fd)==-1) {
printf("pipe failed\n");
return;
}

pid=fork();

if(pid<0)
{
printf("fork failed\n");
return;
}
if(pid>0)//parent
{
close(p2fd[1]);
close(p1fd[0]);
printf("enter the msg to child (Client)--->Parent\n");
scanf("%s",msg);
write(p1fd[1],msg,strlen(msg)+1);
sleep(5);//sleep of 5 seconds
read(p2fd[0],msg,100);
printf("the msg given by child (client) is %s --->Parent\n",msg);
}
else
{
close(p2fd[0]);
close(p1fd[1]);
sleep(3);
read(p1fd[0],msg,100);
printf("the msg given by parent is %s --->child\n",msg);
sleep(3);//sleep of 3 seconds
printf("enter the msg to parent --->child\n");
scanf("%s",msg);
write(p2fd[1],msg,strlen(msg)+1);

}
}

b) Process Communication using FIFOs.


//FIFO create Process
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fd,x;
char msg[100];
x=mkfifo("abc",0666);
if(x==-1)
{
printf("fifo not created\n");
return 0;
}
fd=open("abc",O_WRONLY);
2 if(fd==-1)
{
printf("fifo not opened\n");
return 0;
}
printf("Enter the Message to FIFO ");
scanf("%s",msg);
write(fd,msg,sizeof(msg));
close(fd);
sleep(4);
printf("Message written to FIFO \n");
unlink("abc");
return 0;
}

//FIFO Access Process


#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#define size 1024
int main()
{
int fd;
char buf[size];
fd=open("abc",O_RDONLY);
if(fd==-1){
printf("fifo not opened\n");
return 0;
}
read(fd,buf,size);
printf("\nthe message received from FIFO is --->%s",buf);
close(fd);
return 0;
}

1. What is the return value after pipe () system call is executed?


2. How to perform read and write operations on a pipe
Post-Lab 3. Are the pipes can be used for network access?
Questions 4. How would you differentiate between ordinary pipes and named pipes?
5. Which type of pipes are need to removed explicitly from the system?
6. Is pipes bidirectional? If not how to implement two-way communication.
Week-6 Implement Shared Memory form of IPC.
1. How do we achieve Inter process communication in Operating System?
Pre-Lab 2. What is shared memory? What are the programming paradigms for shared memory?
Questions 3. Describe any two characteristics of shared memory.
4. What are the limitations in implementing shared memory?
//Shared memory - create Process – shmcreate.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include<stdlib.h>
#define SHMSZ 27
void main()
{
char c;
int shmid;
key_t key;
char *shm, *s;

key = 5678;

if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0)


{
printf("Shared Memory cannot be created");
exit(1);
}

if((shm = shmat(shmid, NULL, 0)) == (char *) -1)


{
printf("shared memory cannot be attached);
exit(1);
}

// Write alphabhets into shared memory - server


for (c = 'a'; c <= 'z'; c++)
*shm++ = c;
*shm = NULL;

}
//Shared memory - Access Process – shmaccess.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define SHMSZ 27
void main(){
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
printf("shared memory cannot be opened");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("Can not be attached to shared memory");
exit(1);
}
//Read Alphabets from shared memory
for (s = shm; *s != NULL; s++)
putchar(*s);

putchar('\n');

1. Identify the system calls needed for implementing shared memory?


2. Write the syntax to create a shared memory.
Post-Lab 3. How to attach to the shared memory region?
Questions 4. What is the return value of shmat() system call?
5. How to delete a shared memory region using unix system call?
Week-7 Implement Message Queue form of IPC.
1. How do we achieve Inter process communication in Operating System?
2. What is message queue? What are the applications using shared memory?
3. Describe any two characteristics of Message Passing systems.
Pre-Lab
4. What are the limitations in implementing message passing systems?
Questions
5. How do the direct and indirect communication differs?
6. What are the system calls for symmetric and asymmetric communication?
7. Who own the message queue in message passing systems?
//Message Queue - create and send Process – msgsend.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 128
typedef struct msgbuf {
long mtype;
char mtext[SIZE];
} message_buf;

int main()
{
int msqid;
int msgflg = IPC_CREAT|0666;
key_t key;
message_buf sbuf;
size_t buf_length;
char msg[100];
key = 1234;

if ((msqid = msgget(key, msgflg )) < 0)


{
printf("msgget-msg queue can not be created \n");
return 1;
}
printf("\n Message Queue created with ID = %d\n", msqid);
sbuf.mtype = 1;
printf("\n Enter the message to send \n");
scanf("%s",msg);
strcpy(sbuf.mtext, msg);
buf_length = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {
return 1;
}
else {
printf("\n Message Sent to Message Queue is %s \n", sbuf.mtext);
}
return 1;
}
//Message Queue - Recieve Process – msgrcv.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<stdlib.h>
#define SIZE 128

typedef struct msgbuf


{
long mtype;
char mtext[SIZE];
} message_buf;

int main()
{
int msqid;
key_t key;
message_buf rbuf;
key = 1234;
if ((msqid = msgget(key, 0666)) < 0)
{
printf("msgget- can not open Message Queue");
exit(1);
}

if (msgrcv(msqid, &rbuf, SIZE, 1, 0) < 0)


{
printf("msgrcv- error in recieving");
exit(1);
}
printf("\n Message Recievied From the Queue %s \n", rbuf.mtext);

exit(0);
}

1. Identify the system calls needed for implementing message queues in UNIX?
2. Write the syntax to create and open a message queue?
Post-Lab 3. How to perform read and write operations on message queue?
Questions 4. What is the return value of msgget() system call?
5. How to delete a message queue using unix system call?
6. Differentiate between shared memory and message queues.
Simulate cp, head and tail utilities using file handling
Week-8
system calls.
1. How the cp command works?
2. List various options of cp command?
Pre-Lab
3. How to display beginning lines of a file?
Questions 4. How to display the ending lines of a file?
5. What are command line arguments?
//cp command simulation
#include <stdlib.h>
int main(int argc , int argv[]) {
char ch;
FILE *fp1, *fp2;

fp1 = fopen(argv[1], "r");

if (fp1 == NULL) {
printf("Press any key to exit...\n");
exit(1);
}
fp2 = fopen(argv[2], "w");
if (target == NULL) {
fclose(source);
printf("Press any key to exit...\n");
exit(0);
}
while ((ch = fgetc(source))! = EOF)
fputc(ch, target);
printf("File copied successfully.\n");

fclose(source);
fclose(target);
return 0;
}

cc copy.c -> to compile


./a.out. demo1.txt demo2.txt

// Create demo1.txt file.


//Can use unix system calls also for simulation.
//head command simulation
Create a directory
Create a text file with content. [eg: demo.txt]
Create a C programme using gedit editor.
 cc head.c -> to compile
 ./a.out. 3 demo.txt => to execute. (command line args)
#include<stdio.h>
#include<stdlib.h>
int main(int argc , char *argv[])
{
FILE *fp;
char *line;
int len=0;
int count=0;
if(argc < 3) {
printf("Insuffiecent Arguments");
return -1;
}
fp = fopen(argv[2] , "r");
if(fp == NULL) {
printf("File cannot be opened");
return 1;
}
while(getline(&line,&len,fp)!= -1) {
count++;
if(count > atoi(argv[1]))
break;
printf("%s", line);
fflush(stdout);
}
fclose(fp);
return (0);
}
//tail command simulation
 cc tail.c -> to compile
 ./a.out. 3 demo.txt => to execute. (command line args)
#include<stdio.h>
#include<stdlib.h>
int main(int argc , char *argv[]) {
FILE *fp;
char *line;
int len=0;
int count=0,n,i;
if(argc < 3) {
printf("Insuffiecent Arguments");
return -1;
}
fp = fopen(argv[2] , "r");
if(fp == NULL) {
printf("File cannot be opened");
return 1;
}
while(getline(&line,&len,fp)!= -1) {
count++;
}
printf("\n Total number of lines is %d \n", count);
rewind(fp);
n = count - atoi(argv[1]);
i=0;
while(getline(&line , &len , fp) !=-1) {
i++;
if(i > n)
printf("%s",line);
}
fclose(fp);
return (0);
}
1. What are the unix system calls for reading and writing with a file?
2. What is the use of getline() function and elaborate on it.
Post-Lab 3. Why do we need command line arguments?
Questions 4. Is every command in unix need a system call? If so, demonstrate with an example.
5. What are the system calls required in unix for copying the content from one file
to another.
Week-9 Shell Script programs using control statements.
1) What is shell Script? Does it interpreted or compiled?
Pre-Lab
2) How to combine set of commands to run at a time?
Questions 3) What is the difference between script and program?
a) Write a Shell Script program to check whether a person is eligible to vote.
b) Write a Shell Script program to check a number is even or odd.
c) Write a Shell Script program to find the Grade of a student
d) Write a Shell Script program to implement a simple calculator.

1. Write the syntax to define conditional statements in Shell Script.


2. Write a script to copy contents of one file to another, if destination file exists
Post-Lab
display a message the file cannot be copied.
Questions 3. Write a menu driven program for file operations using case statement.
Week-10 Shell Script programs using control statements.
1. What is the need of case statement?
Pre-Lab
2. Does the shell script allow looping statements?
Questions 3. List the various loop statements in Shell Script?
a) Write a Shell Script program to find the factorial of a number.
b) Write a Shell Script program to find the factorial of a number using while loop.
c) Write a Shell Script program to implement basic calculator using until loop

1. Write the syntax to define iterative statements in Shell Script.


Post-Lab 2. Write a script to copy contents of files into a directory using while loop.
Questions 3. Write a menu driven program for file operations using until statement.
Program to implement FIFO and LRU Page
Week-11
replacement algorithms
1. What is paging? When a page is replaced?
Pre-Lab 2. What are the various page replacement algorithms?
Questions 3. How do the FIFO replacement is implementd?
4. How to replace a page using LRU page replacement?
FIFO Page replacement algorithm
#include<stdio.h>
void main()
{
int i,j,k,m,n;
int pf=0, count=0;
int rs[30], mf[10];

printf("\n Enter the length of the reference string \n");


scanf("%d",&n);
printf("\n Enter the reference string \n");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\n Enter the number of frames \n");
scanf("%d",&m);

for(i=0; i<m;i++)
mf[i] =-1;

printf("\n The FIFO page replacement process is \n");

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


for(k=0;k<m;k++) {
if( mf[k] == rs[i])
break;
}
if(k ==m )
{
mf[count] = rs[i];
count++;
pf++;
}
for(j=0;j<m ;j++)
printf("\t %d",mf[j]);

if(k==m)
printf("\t\tThe page fault no. is %d \n" , pf);
printf("\n");

if(count == m)
count =0;
}
printf(" The total page faults is using FIFO replacement is ---> %d \n ", pf);
}
LRU Page replacement algorithm
#include<stdio.h>
void main() {
int i,j,k,min;
int rs[25], flag[25];
int n,f,pf=0,next=1;
int count[20], m[20];
printf("Enter the length of reference string \n ");
scanf("%d",&n);
printf("\n Enter the reference string --->\n");
for(i=0;i<n;i++)
{
scanf("%d",&rs[i]);
flag[i] = 0;
}
printf(" \n Enter the number of frames \n");
scanf("%d",&f);
for(i=0;i<f;i++)
{
count[i] = 0;
m[i] = -1;
}
printf("\n The Page Replacement process is --->\n" );
for(i=0;i<n;i++) {
for(j=0;j<f;j++) {
if(m[j]==rs[i]) {
flag[i] = 1;
count[j]= next;
next++;
}

if(flag[i] == 0)
{
if(i <f )
{
m[i] = rs[i];
count[i]= next;
next++;
}
else
{
min = 0;
for(j=1;j<f;j++)
if(count[min] > count[j])
min = j;
m[min] = rs[i];
count[min] = next;
next++;
}
pf++;
}
for(j=0 ; j<f;j++)
printf("%d \t",m[j]);

if(flag[i] == 0)
printf(" The Page Fault num is ...>%d" ,pf);
printf("\n");
}
printf("\n The number of page faults using LRU is ---> %d \n" , pf);
}

1. Differentiate between LRU and OPT algorithms.


Post-Lab 2. What is the best page replacement strategy?
Questions 3. What is the input for finding page faults using replacement algorithm?
4. How do we handle a page fault?
Program to implement Disk Scheduling Algorithms – FCFS
Week-12
and SSTF.
1. How do you identify a cylinder in disk pack (hard disk).
2. What is seek time?
Pre-Lab
3. What are the various disk scheduling algorithms?
Questions
4. SSTF disk scheduling stands for ….
5. What is the limitation of FCFS scheduling algorithm.
1. FCFS Disk Scheduling Algorithm
#include <stdio.h>
void fcfs_disk_scheduling(int arr[], int n , int first){
int total_dist = 0;
int distance, current;
int i;
for ( i = 0; i < n; i++) {
current = arr[i];
distance = current - first;
if(distance < 0)
distance=-1*distance;

total_dist += distance;
first = current;
}
printf("Total seek distance is %d" , total_dist);
printf("\n The Seek Sequence is \n");
for (i = 0; i < n; i++) {
printf("%d ",arr[i]);
}
}
int main(){
int arr[100];
int n,i;
int start ;
printf("Enter the total number of cylinder requests in queue");
scanf("%d", &n);
printf("Enter the cylinder numbers requested");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
printf("Enter the initial head position");
scanf("%d",&start);
fcfs_disk_scheduling(arr, n, start);
return 0;
}
Output:
Enter the total number of cylinder requests in queue 8
Enter the cylinder numbers requested 98
183
37
122
14
124
65
67
Enter the initial head position53
Total seek distance is 640
The Seek Sequence is
98 183 37 122 14 124 65 67

2. SSTF Disk Scheduling Algorithm


#include<math.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,k,req[50],mov=0,cp,index[50],min,a[50],j=0,mini,cp1;
printf("enter the current position\n");
scanf("%d",&cp);
printf("enter the number of requests\n");
scanf("%d",&n);
cp1=cp;
printf("enter the request order\n");
for(i=0;i<n;i++)
{
scanf("%d",&req[i]);
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
index[i]=abs(cp-req[i]); // calculate distance of each request from current position
}
// to find the nearest request
min=index[0];
mini=0;
for(i=1;i<n;i++)
{
if(min>index[i])
{
min=index[i];
mini=i;
}
}
a[j]=req[mini];
j++;
cp=req[mini]; // change the current position value to next request
req[mini]=999;
}
// the request that is processed its value is changed so that it is not processed again
printf("Sequence is : ");
printf("%d",cp1);
mov=mov+abs(cp1-a[0]); // head movement
printf(" -> %d",a[0]);
for(i=1;i<n;i++)
{
mov=mov+abs(a[i]-a[i-1]); ///head movement
printf(" -> %d",a[i]);
}
printf("\n");
printf("total head movement = %d\n",mov);
}

1. Describe how SSTF algorithm is working?


2. Which disk scheduling provides minimum seek distance?
Post-Lab
3. How to you satisfy the queue of requests without increasing waiting time?
Questions
4. What are the parameters to be considered in implementing disk scheduling algorithms?
5. What is the input and out for the given disk scheduling algorithm.
Implement Semaphores (Producer-Consumer Problem)
Week-13
using C.
1. What is a semaphore? What are the operations performed on a semaphore?
2. What is busy-waiting? How to resolve the problem?
Pre-Lab 3. How binary and counting semaphores differ? What is need of each one?
Questions 4. What is Synchronization? What are the tools for synchronization?
5. How to define a critical section problem?
6. What are the conditions a critical section problem has to satisfy?
#include <stdio.h>
#include <stdlib.h>
int mutex = 1;
int full = 0;
int empty = 1, x = 0;
// Function to produce an item into a buffer
void producer()
{
--mutex;
++full;
--empty;

printf("Enter an item to produce");


scanf("%d",&x);// Item produced

printf("\nProducer produces item %d",x);


++mutex;
}

// Function to consume an item and remove it from buffer


void consumer()
{
--mutex;
--full;
++empty;
printf("\nConsumer consumes item %d",x);
x=0;
++mutex;
}

int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");

for (i = 1; i > 0; i++) {


printf("\nEnter your choice:");
scanf("%d", &n);
switch (n) {
case 1: if ((mutex == 1) && (empty != 0)) {
producer();
}
else {
printf("Buffer is full!");
}
break;

case 2: if ((mutex == 1) && (full != 0)) {


consumer();
}
else {
printf("Buffer is empty!");
}
break;
case 3:
exit(0);
break;
}
}
}

1. What is bounded and unbounded buffer?


2. Write the definition of wait() and signal() operations.
Post-Lab 3. How to achieve mutual exclusion using semaphores?
Questions 4. Write the definition for modified wait() and signal() operations.
5. How do semaphores are best synchronization tool?

You might also like