Professional Documents
Culture Documents
and Engineering
Prepared
by
Mr.V.BALU
Assistant Professor
1
OPERATING SYSTEMS LAB MANUAL INDEX
2
OPERATING SYSTEMS LAB MANUAL INDEX
3
What is Unix ?
The UNIX operating system is a set of programs that act as a link between the computer and the user.
The computer programs that allocate the system resources and coordinate all the details of the
computer's internals is called the operating system or kernel. Users communicate with the kernel
through a program known as the shell. The shell is a command line interpreter; it translates commands
entered by the user and converts them into a language that is understood by the kernel.
Unix was originally developed in 1969 by a group of AT&T employees at Bell Labs, including
Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.
There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are
few examples. Linux is also a flavor of Unix which is freely available.
Several people can use a UNIX computer at the same time; hence UNIX is called a multiuser
system.
A user can also run multiple programs at the same time; hence UNIX is called multitasking.
Unix Architecture
The main concept that unites all versions of UNIX is the following four basics:
Kernel: The kernel is the heart of the operating system. It interacts with hardware and most of
the tasks like memory management, tash scheduling and file management.
Shell: The shell is the utility that processes your requests. When you type in a command at your
terminal, the shell interprets the command and calls the program that you want. The shell uses
4
standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are most famous shells
which are available with most of the Unix variants.
Commands and Utilities: There are various command and utilities which you would use in your
day to day activities. cp, mv, cat and grep etc. are few examples of commands and utilities.
There are over 250 standard commands plus numerous others provided through 3rd party
software. All the commands come along with various optional options.
Files and Directories: All data in UNIX is organized into files. All files are organized into
directories. These directories are organized into a tree-like structure called the files system
All data in UNIX is organized into files. All files are organized into directories. These directories are
organized into a tree-like structure called the filesystem.
You can use ls command to list out all the files or directories available in a directory. Following is the
example of using ls command with -l option.
Pwd
pwd stands for Print Working Directory. It prints the path of the working directory, starting from the
root. pwd is shell built-in command(pwd) or an actual binary(/bin/pwd).
$PWD is an environment variable which stores the path of the current directory.
This command has two flags.
pwd -L: Prints the symbolic path.
pwd -P: Prints the actual path.
5
Unix Directories
A directory is a file whose sole job is to store file names and related information. All files whether
ordinary, special, or directory, are contained in directories. UNIX uses a hierarchical structure for
organizing files and directories. This structure is often referred to as a directory tree .
The tree has a single root node, the slash character ( /), and all other directories are contained below it.
Home Directory: The directory in which you find yourself when you first login is called your home
directory. You will be doing much of your work in your home directory and subdirectories that you'll be
creating to organize your files. You can go in your home directory anytime using the following
command:
$cd ~ $
Here ~ indicates home directory. If you want to go in any other user's home directory then use the
following command:
$cd ~username $
$cd –
Absolute/Relative Pathnames:
Directories are arranged in a hierarchy with root (/) at the top. The position of any file within the
hierarchy is described by its pathname. Elements of a pathname are separated by a /. A pathname is
absolute if it is described in relation to root, so absolute pathnames always begin with a /. These are
some example of absolute filenames
A pathname can also be relative to your current working directory. Relative pathnames never begin with
/. Relative to user amrood' home directory, some pathnames might look like this:
chem/notes personal/res
To determine where you are within the filesystem hierarchy at any time, enter the command pwd to
print the current working directory:
$pwd /user0/home/amrood $
6
Listing Directories:
To list the files in a directory you can use the following syntax:
$ls dirname
Following is the example to list all the files contained in /usr/local directory:
Following is the example to list all the files contained in /usr/local directory:
Creating Directories:
Directories are created by the following command:
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to create. For example,
the command:
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example:
$mkdir /tmp/test-dir
$
This command creates the directory test-dir in the /tmp directory. The mkdir command produces no
output if it successfully creates the requested directory.
If you give more than one directory on the command line, mkdir creates each of the directories. For
example:
7
Removing Directories:
Directories can be deleted using the rmdir command as follows:
$rmdir dirname
$
Note: To remove a directory make sure it is empty which means there should not be any file or sub-
directory inside this directory.
You can create multiple directories at a time as follows:
Above command removes the directories dirname1, dirname2, and dirname2 if they are empty. The
rmdir command produces no output if it is successful.
Changing Directories:
You can use the cd command to do more than change to a home directory: You can use it to change to
any directory by specifying a valid absolute or relative path. The syntax is as follows:
$cd dirname
$
Here, dirname is the name of the directory that you want to change to. For example, the command:
$cd /usr/local/bin
$
Changes to the directory /usr/local/bin. From this directory you can cd to the directory
/usr/home/amrood using the following relative path:
$cd ../../home/amrood
$
Renaming Directories:
The mv (move) command can also be used to rename a directory. The syntax is as follows:
8
Cat command
Cat(concatenate ) command is very frequently used in linux.It reads data from file and give their content
as output.It helps us to create,view,concatenate files.So let us see some frequently used cat commands.
9
4) Create a file
Command:
$ cat >newfile
Output
Will create and a file named newfile
5) Copy the contents of one file to another file.
Command:
$cat [filename-whose-contents-is-to-be-copied] > [destination-filename]
Output
The content will be copied in destination file
6) Cat command can suppress repeated empty lines in output
Command:
$cat -s geeks.txt
Output
Will suppress repeated empty lines in output
7) Cat command can append the contents of one file to the end of another file.
Command:
$cat file1 >> file2
Output
Will append the contents of one file to the end of another file
8) Cat command can display content in reverse order using tac command.
Command:
$tac filename
Output
Will display content in reverse order
9) Cat command can highlight the end of line.
Command:
$cat -E "filename"
Output
Will highlight the end of line
10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the command,
you can just use the -A command line option.
Command
$cat -A "filename"
10
mv command
mv stands for move. mv is used to move one or more files or directories from one place to another in
file system like UNIX. It has two distinct functions:
(i) It rename a file or folder.
(ii) It moves group of files to different directory.
No additional space is consumed on a disk during renaming. This command normally works
silently means no prompt for confirmation.
Syntax:
mv [Option] source destination
Let us consider 5 files having name a.txt, b.txt and so on till e.txt.
To rename the file a.txt to geek.txt(not exist):
$ ls
a.txt b.txt c.txt d.txt
$ mv a.txt geek.txt
$ ls
b.txt c.txt d.txt geek.txt
If the destination file doesn’t exist, it will be created. In the above command mv simply replaces the
source filename in the directory with the destination filename(new name). If the destination file exist,
then it will be overwrite and the source file will be deleted. By default, mv doesn’t prompt for
overwriting the existing file, So be careful
rm command
rm stands for remove here. rm command is used to remove objects such as files, directories, symbolic
links and so on from the file system like UNIX. To be more precise, rm removes references to objects
from the filesystem, where those objects might have had multiple references (for example, a file with
two different names). By default, it does not remove directories.
This command normally works silently and you should be very careful while running rm command
because once you delete the files then you are not able to recover the contents of files and directories.
Syntax:
rm [OPTION]... FILE...
Let us consider 5 files having name a.txt, b.txt and so on till e.txt.
$ ls
a.txt b.txt c.txt d.txt e.txt
Removing one file at a time
$ rm a.txt
$ ls
b.txt c.txt d.txt e.txt
$ ls
d.txt e.txt
Note: No output is produced by rm, since it typically only generates messages in the case of an error.
11
options:
1. -i (Interactive Deletion): Like in cp, the -i option makes the command ask the user for confirmation
before removing each file, you have to press y for confirm deletion, any other key leaves the file un-
deleted.
$ rm -i d.txt
rm: remove regular empty file 'd.txt'? y
$ ls
e.txt
2. -f (Force Deletion): rm prompts for confirmation removal if a file is write protected. The -f option
overrides this minor protection and removes the file forcefully.
$ ls -l
total 0
-r--r--r--+ 1 User User 0 Jan 2 22:56 e.txt
$ rm e.txt
rm: remove write-protected regular empty file 'e.txt'? n
$ ls
e.txt
$ rm -f e.txt
$ ls
3. -r (Recursive Deletion): With -r(or -R) option rm command performs a tree-walk and will delete all
the files and sub-directories recursively of the parent directory. At each stage it deletes everything it
finds. Normally, rm wouldn’t delete the directories but when used with this option, it will delete.
Below is the tree of directories and files:
$ ls
A
$ cd A
$ ls
B C
$ ls B
a.txt b.txt
$ ls C
c.txt d.txt
12
rm: cannot remove 'B': Is a directory
rm: cannot remove 'C': Is a directory
$ rm -r *
$ ls
4. –version: This option is used to display the version of rm which is currently running on your system.
$ rm --version
rm (GNU coreutils) 8.26
Packaged by Cygwin (8.26-2)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Paul Rubin, David MacKenzie, Richard M. Stallman,
and Jim Meyering.
13
PROCESS AND STATUS INFORMATION COMMANDS
Simple process selection : Shows the processes for the current shell –
[root@rhel7 ~]# ps
PID TTY TIME CMD
12330 pts/0 00:00:00 bash
21621 pts/0 00:00:00 ps
Result contains four columns of information.
Where,
PID – the unique process ID
TTY – terminal type that the user is logged into
TIME – amount of CPU in minutes and seconds that the process has been running
CMD – name of the command that launched the process.
Note – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but
the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time
has been given by the kernel till now. In above example we found that, for bash no CPU time has
been given. This is because bash is just a parent process for different processes which needs bash
for their execution and bash itself is not utilizing any CPU time till now.
1. View Processes : View all the running processes use either of the following option with ps –
[root@rhel7 ~]# ps -A
[root@rhel7 ~]# ps -e
14
View Processes not associated with a terminal : View all processes except both session leaders and
processes not associated with a terminal.
[root@rhel7 ~]# ps -a
PID TTY TIME CMD
27011 pts/0 00:00:00 man
27016 pts/0 00:00:00 less
27499 pts/1 00:00:00 ps
Note – You may be thinking that what is session leader? A unique session is assing to evry
process group. So, session leader is a process which kicks off other processes. The process ID of
first process of any session is similar as the session ID.
3. View all processes except those that fulfill the specified conditions (negates the selection) :
Example – If you want to see only session leader and processes not associated with a terminal.
Then, run
[root@rhel7 ~]# ps -a -N
OR
[root@rhel7 ~]# ps -a --deselect
6. View all processes owned by you : Processes i.e same EUID as ps which means runner of the ps
command, root in this case –
[root@rhel7 ~]# ps -x
15
Examples :
1. The who command displays the following information for each user currently logged in to the system
if no option is provided :
1. Login name of the users
2. Terminal line numbers
3. Login time of the users in to system
4. Remote host name of the user
hduser@mahesh-Inspiron-3543:~$ who
hduser tty7 2018-03-18 19:08 (:0)
hduser@mahesh-Inspiron-3543:~$
whoami command in Linux with example
whoami command is used both in UNIX OPERATING SYSTEM and as well as in WINDOWS
OPERATING SYSTEM .
The earliest versions were created in 2.9 BSD as a convenience form for who am i, the Berkeley Unix
who command’s way of printing just the logged in user’s identity. The GNU version was written by
Richard Mlynarik and is part of the GNU Core Utilities (coreutils).
$ whoami
Amrood
Following is a simple example of date command which displays current date and time:
$date
Syntax :
echo [string]
Example :
16
TEXT RELATED COMMANDS
Without any option it display only the first 10 lines of the file specified.
Example:
$ head state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
17
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
1. -n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory to be specified in
command otherwise it displays an error.
$ head -n 5 state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
2. -c num: Prints the first ‘num’ bytes from the file specified. Newline count as a single character, so if
head prints out a newline, it will count it as a byte. num is mandatory to be specified in command
otherwise displays an error.
$ head -c 6 state.txt
Andhra
3. -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.
Without using -q option
==> state.txt capital.txt <==
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
18
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
4. -v: By using this option, data from the specified file is always preceded by its file name.
$ head -v state.txt
==> state.txt <==
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
19
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Without any option it display only the last 10 lines of the file specified.
Example:
$ tail state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
1. -n num: Prints the last ‘num’ lines instead of last 10 lines. num is mandatory to be specified in
command otherwise it displays an error. This command can also be written as without symbolizing ‘n’
character but ‘-‘ sign is mandatory.
$ tail -n 3 state.txt
Uttar Pradesh
Uttarakhand
West Bengal
OR
$ tail -3 state.txt
Uttar Pradesh
20
Uttarakhand
West Bengal
Tail command also comes with an ‘+’ option which is not present in the head command. With this
option tail command prints the data starting from specified line number of the file instead of end. For
command: tail +n file_name, data will start printing from line number ‘n’ till the end of the file specified.
$ tail +25 state.txt
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
2. -c num: Prints the last ‘num’ bytes from the file specified. Newline count as a single character, so if
tail prints out a newline, it will count it as a byte. In this option it is mandatory to write -c followed by
positive or negative num depends upon the requirement. By +num, it display all the data after
skipping num bytes from starting of the specified file and by -num, it display the last num bytes from
the file specified.
Note: Without positive or negative sign before num, command will display the last numbytes from the
file specified.
With negative num
$ tail -c -6 state.txt
Bengal
OR
$ tail -c 6 state.txt
Bengal
21
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi
22
Uttar Pradesh
Uttarakhand
West Bengal
6. –version: This option is used to display the version of tail which is currently running on your system.
$ tail --version
tail (GNU coreutils) 8.26
Packaged by Cygwin (8.26-1)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Paul Rubin, David MacKenzie, Ian Lance Taylor,
and Jim Meyering.
$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
Passing only one file name in the argument.
$ wc state.txt
5 7 63 state.txt
OR
$ wc capital.txt
5 5 45 capital.txt
23
Passing more than one file name in the argument.
$ wc state.txt capital.txt
5 7 63 state.txt
5 5 45 capital.txt
10 12 108 total
Note : When more than file name is specified in argument then command will display four-columnar
output for all individual files plus one extra row displaying total number of lines, words and characters
of all the files specified in argument, followed by keyword total.
Options:
1. -l: This option prints the number of lines present in a file. With this option wc command displays
two-columnar output, 1st column shows number of lines present in a file and 2nd itself represent the
file name.
With one file name
$ wc -l state.txt
5 state.txt
24
63 state.txt
45 capital.txt
108 total
5. -L: The ‘wc’ command allow an argument -L, it can be used to print out the length of longest
(number of characters) line in a file. So, we have the longest character line Arunachal Pradesh in a
file state.txt and Hyderabad in the file capital.txt. But with this option if more than one file name is
specified then the last row i.e. the extra row, doesn’t display total but it display the maximum of all
values displaying in the first column of individual files.
Note: A character is the smallest unit of information that includes space, tab and newline.
With one file name
$ wc -L state.txt
17 state.txt
$ ls gfg | wc -l
7
2. Display number of word count only of a file: We all know that this can be done with wccommand
having -w option, wc -w file_name, but this command shows two-columnar output one is count of
words and other is file name.
$ wc -w state.txt
25
7 state.txt
So to display 1st column only, pipe(|) output of wc -w command to cut command with -coption. Or use
input redirection(<).
$ wc -w state.txt | cut -c1
7
OR
$ wc -w < state.txt
7
26
1. Search a file with specific name.
$ find ./GFG -name sample.txt
It will search for sample.txt in GFG directory.
Output :
27
4. Search for empty files and directories.
$ find ./GFG -empty
This command find all empty folders and files in the entered directory or sub-directories.
Output :
28
File Permission Commands
File ownership is an important component of UNIX that provides a secure method for storing files.
Every file in UNIX has the following attributes:
Owner permissions: The owner's permissions determine what actions the owner of the file can perform
on the file.
Group permissions: The group's permissions determine what actions a user, who is a member of the
group that a file belongs to, can perform on the file.
Other (world) permissions: The permissions for others indicate what action all other users can perform
on the file.
While using ls -l command it displays various information related to file permission as follows:
Here first column represents different access mode ie. permission associated with a file or directory.
The permissions are broken into groups of threes, and each position in the group denotes a specific
permission, in this order: read (r), write (w), execute (x):
The first three characters (2-4) represent the permissions for the file's owner. For example -rwxr-xr--
represents that onwer has read (r), write (w) and execute (x) permission.
The second group of three characters (5-7) consists of the permissions for the group to which the file
belongs. For example -rwxr-xr-- represents that group has read (r) and execute (x) permission
The permissions of a file are the first line of defense in the security of a Unix system. The basic building
blocks of Unix permissions are the read, write, and execute permissions, which are described below:
1. Read: Grants the capability to read ie. view the contents of the file.
2. Write: Grants the capability to modify, or remove the content of the file.
29
Directory Access Modes:
Directory access modes are listed and organized in the same manner as any other file. There are a few
differences that need to be mentioned:
1. Read: Access to a directory means that the user can read the contents. The user can
look at the filenames inside the directory.
2. Write: Access means that the user can add or delete files to the contents of the
directory.
3. Execute: Executing a directory doesn't really make a lot of sense so think of this as a
traverse permission.
A user must have execute access to the bin directory in order to execute ls or cd command.
Changing Permissions:
To change file or directory permissions, you use the chmod (change mode) command. There are two
ways to use chmod: symbolic mode and absolute mode.
30
Using chmod with Absolute Permissions:
The second way to modify permissions with the chmod command is to use a number to specify each set
of permissions for the file.
Each permission is assigned a value, as the following table shows, and the total of each set of
permissions provides a number for that set.
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
31
Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you
can see the permission changes:
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the
permissions mentioned above are also assigned based on Owner and Groups.
Two commands are available to change the owner and the group of files:
1. chown: The chown command stands for "change owner" and is used to change the owner of a file.
2. chgrp: The chgrp command stands for "change group" and is used to change the group of a file.
Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as follows:
The value of user can be either the name of a user on the system or the user id (uid) of a user on the
system.
Following example:
NOTE: The super user, root, has the unrestricted capability to change the ownership of a any file but
normal users can change only the owner of files they own.
Changing Group Ownership:
The chrgp command changes the group ownership of a file. The basic syntax is as follows:
The value of group can be the name of a group on the system or the group ID (GID) of a group on the
system.
Following example:
32
2. SHELL PROGRAMMING
What is a Shell?
An Operating is made of many components, but its two prime components are -
Kernel
Shell
A Kernel is at the nucleus of a computer. It makes the communication between the hardware and
software possible. While the Kernel is the innermost part of an operating system, a shell is the
outermost one.
A shell in a Linux operating system takes input from you in the form of commands, processes it, and
then gives an output. It is the interface through which a user works on the programs, commands, and
scripts. A shell is accessed by a terminal which runs it.
When you run the terminal, the Shell issues a command prompt (usually $), where you can type your
input, which is then executed when you hit the Enter key. The output or the result is thereafter
displayed on the terminal.
The Shell wraps around the delicate interior of an Operating system protecting it from accidental
damage. Hence the name Shell.
Types of Shell
1. The Bourne Shell: The prompt for this shell is $ and its derivatives are listed below:
33
2. The C shell: The prompt for this shell is %, and its subcategories are:
Shell scripting is writing a series of command for the shell to execute. It can combine lengthy and
repetitive sequences of commands into a single and simple script, which can be stored and executed
anytime. This reduces the effort required by the end user.
1. Create a file using a vi editor(or any other editor). Name script file with extension .sh
2. Start the script with #! /bin/sh
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh
"#!" is an operator called shebang which directs the script to the interpreter location. So, if we use"#!
/bin/sh" the script gets directed to the bourne-shell.
#!/bin/sh
ls
34
Adding shell comments
Commenting is important in any program. In Shell programming, the syntax to add a comment is
#comment
As discussed earlier, Variables store data in the form of characters and numbers. Similarly, Shell
variables are used to store information and they can by the shell only.
For example, the following creates a shell variable and then prints it:
variable ="Hello"
echo $variable
#!/bin/sh
echo "what is your name?"
read name
echo "How do you do, $name?"
read remark
echo "I am $remark too!"
35
As you see, the program picked the value of the variable 'name' as Joy and 'remark' as excellent.
This is a simple script. You can develop advanced scripts which contain conditional statements, loops,
and functions. Shell scripting will make your life easy and Linux administration a breeze.
Example Program
36
Biggest of three numbers
echo "enter three numbers"
read a b c
if [ $a -gt $b ] && [ $a -gt $c ]
then
echo "A is big" else if [ $b -gt $c ] then
echo "B is big" else
echo "C is big"
fi
fi
factorial
Fibonacci series
37
3. Unix Pipes and Filters
a) Grep Commnd
The grep filter searches a file for a particular pattern of characters, and displays all lines that contain
that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands
for globally search for regular expression and print out).
Syntax:
More than two commands may be linked up into a pipe. Taking a previous pipe example using grep, we
can further sort the files modified in August by order of size.
The following pipe consists of the commands ls, grep, and sort:
This pipe sorts all files in your directory modified in August by order of size, and prints them to the
terminal screen. The sort option +4n skips four fields (fields are separated by blanks) then sorts the
lines in numeric order.
a) SED COMMAND
SED command in UNIX is stands for stream editor and it can perform lot’s of function on file like,
searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX
is for substitution or for find and replace. By using SED you can edit files even without opening it,
which is much quicker way to find and replace something in file, than first opening that file in VI Editor
and then changing it.
SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution).
SED command in unix supports regular expression which allows it perform complex pattern matching.
39
Syntax:
sed OPTIONS... [SCRIPT] [INPUTFILE...]
> vi file.txt
unix is great os.
unix is open source.
unix is free os.
learn operating system.
unixlinux which one you choose.
OUTPUT :
linux is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you choose.
2. >sed 's/unix/linux/2' file.txt
OUTPUT :
unix is great os. linux is opensource. unix is free os.
learn operating system.
unixlinux which one you choose.
3. >sed 's/unix/linux/g' file.txt
OUTPUT :
linux is great os. linux is opensource. linux is free os.
learn operating system.
linuxlinux which one you choose.
OUTPUT :
unix is great os. unix is opensource. linux is free os.
learn operating system.
unixlinux which one you choose.
OUTPUT :
linux is great os. unix is opensource. unix is free os.
linux is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which
one you choose.
linuxlinux which one you choose
40
6. > sed 's/unix/linux/' file.txt| sed 's/os/system/'
OUTPUT :
linux is great system. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you chosysteme.
7. a) > sed '2 d' file.txt
b) > sed '5,$ d' file.txt
OUTPUT :
Deleting lines.
41
c) Awk Working Methodology
1. Awk reads the input files one line at a time.
2. For each line, it matches with given pattern in the given order, if matches performs the
corresponding action.
3. If no pattern matches, no action will be performed.
4. In the above syntax, either search pattern or action are optional, But not both.
5. If the search pattern is not given, then Awk performs the given actions for each line of the input.
6. If the action is not given, print all that lines that matches with the given patterns which is the default
action.
7. Empty braces with out any action does nothing. It wont perform default printing operation.
8. Each statement in Actions should be delimited by semicolon.
$cat employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
42
Nisha $9,500
Randy $6,000
43
4. SYSTEM CALLS
AIM :
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
int main(void)
{
char *path,path1[10];
struct stat *nfile;
nfile=(struct stat *) malloc (sizeof(struct stat)); printf("enter name of file whose stsistics has to");
scanf("%s",path1);
stat(path1,nfile);
printf("user id %d\n",nfile->st_uid); printf("block size :%d\n",nfile->st_blksize); printf("last access time
%d\n",nfile->st_atime);
printf("time of last modification %d\n",nfile->st_atime); printf("porduction mode %d \n",nfile->st_mode);
printf("size of file %d\n",nfile->st_size);
printf("number of links:%d\n",nfile->st_nlink);}
OUTPUT:
44
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(WAIT())
AIM :
ALGORITHM :
PROGRAM :
#include<stdio.h>
#include<unistd.h>
int main(void)
{
int pid,status,exitch;
if((pid=fork())==-1)
{
perror("error");
exit (0);
}
if(pid==0)
{
sleep(1);
printf("child process");
exit (0);
}
else
{
printf("parent process\n");
if((exitch=wait(&status))==-1)
{
perror("during wait()");
exit (0);
}
printf("\nparent existing\n");
exit (0);}}
OUTPUT :
Parent process
Child process
parent existing
45
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(GETPID() )
AIM: To Execute a Unix Command in a ‘C’ program using getpid() system call.
ALGORITHM:
PROGRAM :
#include<stdio.h>
int main()
{
int pid;
pid=getpid();
printf("process ID is %d\n",pid);
pid=getppid();
printf("parent process ID id %d\n",pid);
}
OUTPUT :
process ID is 2848
parent process ID id 2770
46
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(OPENDIR, READDIR)
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc,char *argv[])
{
char buff[256]; DIR *dirp;
printf("\n\nEnter directory name"); scanf("%s",buff); if((dirp=opendir(buff))==NULL)
{
printf("Error");
exit(1);
}
while(dptr=readdir(dirp))
{
printf("%s\n",dptr->d_name);
}
closedir(dirp);
}
Output:
47
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(OPEN())
AIM : To Execute a Unix Command in a ‘C’ program using open() system call.
ALGORITHM :
PROGRAM :
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
int fd; fd=creat("file1.dat",S_IREAD|S_IW RITE);
if(fd== -1)
{
printf("Error in opening file1.dat\n");
}
else
{
printf("\nfile1.dat opened for read/write access\n");
}
printf("\nfile1.dat is currently empty");
close(fd);
}
OUTPUT:
48
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(OPEN, READ &WRITE)
AIM : To implement UNIX I/O system calls open, read , write etc.
ALGORITHM :
1. Create a new file using creat command (Not using FILE pointer).
2. Open the source file and copy its content to new file using read and write command.
3. Find size of the new file before and after closing the file using stat command.
PROGRAM :
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
static char message[]="hai Hello world";
int main()
{
int fd;
char buffer[80]; fd=open("new2file.txt",O_RDWR|O_CREAT|O_EXCL,S_IREAD|S_IWRITE); if(fd!=-1)
{
printf("new2file.txt opened for read/write access\n");
write(fd,message,sizeof(message)); lseek(fd,0l,0); if(read(fd,buffer,sizeof(message))==sizeof(message))
printf("\"%s\" was written to new2file.txt\n",buffer);
else
printf("***Error readind new2file.txt***\n");
}
else
{
close(fd);
}
printf("***new2file.txt already exists***\n");
}
OUTPUT:
new2file.txt opened for read/write access
"hai Hello world" was written to new2file.txt
49
5. PROCESS MANAGEMENT(fork( ))
AIM:
ALGORITHM:
PROGRAM:
#include<stdio.h>
int main(void)
{
int fork(void),value;
value=fork();
printf("main:value =%d\n",value);
return 0;
}
Output:
main:value =0
main:value =2860
50
5. PROCESS MANAGEMENT(exec( ))
AIM: To Execute a Unix Command in a ‘C’ program using exec() system call.
ALGORITHM:
PROGRAM:
#include<stdio.h>
main()
{
int pid;
char *args[]={"/bin/ls","-l",0}; printf("\nParent Process"); pid=fork();
if(pid==0)
{
execv("/bin/ls",args);
printf("\nChild process");
}
else
{
wait();
printf("\nParent process");
}
exit(0);
}
OUTPUT:
total 440
-rwxrwxr-x 1 skec25 skec25 5210 Apr 16 06:25 a.out
-rw-rw-r-- 1 skec25 skec25 775 Apr 9 08:36 bestfit.c
-rw-rw-r-- 1 skec25 skec25 1669 Apr 10 09:19 correctpipe.c
-rw-rw-r-- 1 skec25 skec25 977 Apr 16 06:15 correctprio.c
-rw------- 1 skec25 skec25 13 Apr 10 08:14 datafile.dat
-rw------- 1 skec25 skec25 13 Apr 10 08:15 example.dat
-rw-rw-r-- 1 skec25 skec25 166 Apr 16 06:25 exec.c
-rw-rw-r-- 1 skec25 skec25 490 Apr 10 09:43 exit.c
Parent Process
51
6. CPU Scheduling Algorithms
AIM:
To write a program to implement the FIFO (FIRST –IN FIRST -OUT) CPU scheduling Algorithm
ALGORITHM:
PROGRAM:
#include<stdio.h>
struct process
{
int burst,wait;
}p[20]={0,0};
int main()
{
int n,i,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
scanf("%d",&p[i].burst);
}
printf("\nProcess \t Waiting Time TurnAround Time ");
printf("\n \t (in ms) (in ms)");
for(i=0;i<n;i++)
{
printf("\nProcess # %-12d%-15d%-15d",i+1,p[i].wait,p[i].wait+p[i].burst);
p[i+1].wait=p[i].wait+p[i].burst;
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
52
printf("\n\nAVERAGE\n--------- ");
printf("\nWaiting Time : %f ms",totalwait/(float)n); printf("\nTurnAround Time : %f
ms\n\n",totalturn/(float)n); return 0;
}
Output:
AVERAGE
---------
Waiting Time : 16.666667 ms
TurnAround Time : 36.666667 ms
RESULT:
Thus the program to implement the FCFS (First Come First Serve) CPU scheduling
Algorithm was written, executed and the output was verified successfully.
53
Ex.No:6(b) ROUND ROBIN CPU SCHEDULING ALGORITHM
Date:
AIM:
ALGORITHM:
#include<stdio.h>
#include<conio.h>
int TRUE = 0;
int FALSE = -1;
int tbt[30],bt[30],tat[30],n=0,wt[30],qt=0,tqt=0,time=0,lmore,t_tat=0,t_wt=0;
void main()
{
int i,j;
clrscr();
printf("\nEnter no. of processors:");
scanf("%d",&n);
printf("\nEnter Quantum Time:");
scanf("%d",&qt);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time of Processor[%d]:",i+1);
scanf("%d",&bt[i]);
tbt[i] = bt[i];
wt[i] = tat[i] = 0;
}
lmore = TRUE;
while(lmore == TRUE)
{
lmore = FALSE;
54
for(i=0;i<n;i++)
{
if(bt[i] != 0)
wt[i] = wt[i] + (time - tat[i]);
tqt = 1;
while(tqt <= qt && bt[i] !=0)
{
lmore = TRUE; bt[i] = bt[i] -1; tqt++;
time++;
tat[i] = time;
}
}
}
printf("\nProcessor ID\tBurstTime\tTurnAroundTime\tWaitingTime\n");
for(i=0;i<n;i++)
{
printf("Processor%d\t\t%d\t\t%d\t\t%d\n",i+1,tbt[i],tat[i],wt[i]);
t_tat = t_tat + tat[i];
t_wt = t_wt + wt[i];
}
printf("\nTotal Turn Around Time:%d",t_tat); printf("\nAverage Turn Around Time:%d",t_tat/n);
printf("\nTotal Waiting Time:%d",t_wt); printf("\nAverage Waiting Time:%d",t_wt/n);
getch();
}
55
7. PROCESS SYNCHRONIZATION
AIM :
ALGORTIHM :
PROGRAM :
#include<stdio.h>
int n=0,buffersize=0,currentsize=0;
void producer()
{
printf("\nEnter number of elements to be produced: ");
scanf("%d",&n);
if(0<=(buffersize-(currentsize+n)))
{
currentsize+=n;
printf("%d Elements produced by producer where buffersize is %d\n", currentsize, buffersize);
}
else
printf("\nBuffer is not sufficient\n");
}
void consumer()
{
int x;
printf("\nEnter no. of elements to be consumed: ");
scanf("%d",&x);
if(currentsize>=x)
{
currentsize-=x;
56
printf("\nNumber of elements consumed: %d, Number of Elements left: %d", x, currentsize);
}
else
{
printf("\nNumber of Elements consumed should not be greater than Number of Elements produced\n");
}
}
void main()
{
int c;
printf("\nEnter maximum size of buffer:");
scanf("%d",&buffersize);
do
{
printf("\n1.Producer 2.Consumer 3.Exit");
printf("\nEnter Choice:");
scanf("%d",&c);
switch(c)
{
case 1:
if(currentsize >= buffersize)
printf("\nBuffer is full. Cannot produce");
else producer();
break;
case 2:
if(currentsize <= 0)
printf("\nBuffer is Empty. Cannot consume");
else
consumer();
break;
default: break;
} }
while(c!=3);
}
OUTPUT :
57
7. PROCESS SYNCHRONIZATION
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define THINKING 0
#define HUNGRY 1
#define EATING 2
#define LEFT (ph_num+4)%N
#define RIGHT (ph_num+1)%N
sem_t mutex;
sem_t S[N];
void * philospher(void *num);
void take_fork(int);
void put_fork(int);
void test(int);
int state[N];
int phil_num[N]={0,1,2,3,4};
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&mutex,0,1);
for(i=0;i<N;i++)
sem_init(&S[i],0,0);
for(i=0;i<N;i++)
{
pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);
printf("Philosopher %d is thinking\n",i+1);
}
for(i=0;i<N;i++)
pthread_join(thread_id[i],NULL);
}
58
void *philospher(void *num)
{
while(1)
{
int *i = num;
sleep(1);
take_fork(*i);
sleep(0);
put_fork(*i);
}
}
void take_fork(int ph_num)
{
sem_wait(&mutex);
state[ph_num] = HUNGRY;
printf("Philosopher %d is Hungry\n",ph_num+1);
test(ph_num);
sem_post(&mutex);
sem_wait(&S[ph_num]);
sleep(1);
}
void test(int ph_num)
{
if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
{
state[ph_num] = EATING;
sleep(2);
printf("Philosopher %d takes fork %d and %d\n",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is Eating\n",ph_num+1);
sem_post(&S[ph_num]);
}
}
void put_fork(int ph_num)
{
sem_wait(&mutex);
state[ph_num] = THINKING;
printf("Philosopher %d putting fork %d and %d down\n",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is thinking\n",ph_num+1);
test(LEFT);
test(RIGHT);
sem_post(&mutex);
}
OUTPUT:
Don’t forgot to link pthread when compiling. It can be done by compiling with -lpthread option. eg: gcc
-lpthread philospher.c
Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 3 is thinking
Philosopher 4 is thinking
Philosopher 5 is thinking
59
Philosopher 1 is Hungry
Philosopher 1 takes fork 5 and 1
Philosopher 1 is Eating
Philosopher 2 is Hungry
Philosopher 3 is Hungry
Philosopher 3 takes fork 2 and 3
Philosopher 3 is Eating
Philosopher 4 is Hungry
Philosopher 5 is Hungry
Philosopher 1 putting fork 5 and 1 down
Philosopher 1 is thinking
Philosopher 5 takes fork 4 and 5
Philosopher 5 is Eating
Philosopher 3 putting fork 2 and 3 down
Philosopher 3 is thinking
60
8. DEADLOCK MANAGEMENT TECHNIQUES
BANKERS ALGORITHM
ALGORTIHM :
Step 1: start
Step 2: Read the number of processes n.
Step 3: Read the number of resources nor.
Step 4: Read the available resources vector avail, allocation matrix all, and maximum . Matrix max.
Step 5: Initialise the matrix need using needi=maxi-all. For i = 1,2,…,n…
Step 6: Call safety algorithm.
Step 7: Call resource request.
Step 8: Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int k=0 , output[10], d=0,t=0,ins[5],i, avail[5],allocated[10][5], need[10][5], MAX[10][5], pno , P[10] , j , rz,
count=0;
clrscr();
printf("\n EnteSSSr the number of resources : ");
scanf("%d", &rz);
printf("\n enter the max instances of each resources\n");
for(i=0;i<rz;i++)
{ avail[i]=0;
printf("%c= ",(i+97));
scanf("%d",&ins[i]);
}
printf("\n Enter the number of processes : ");
scanf("%d", &pno);
printf("\n Enter the allocation matrix \n ");
for(i=0;i<rz;i++)
printf(" %c",(i+97));
printf("\n");
for(i=0;i <pno;i++)
{ P[i]=i;
printf("P[%d] ",P[i]);
for(j=0;j<rz;j++)
{
scanf("%d",&allocated[i][j]);
avail[j]+=allocated[i][j];
}
}
printf("\nEnter the MAX matrix \n ");
for(i=0;i<rz;i++)
{ printf(" %c",(i+97));
61
avail[i]=ins[i]-avail[i];
}
printf("\n");
for(i=0;i <pno;i++)
{
printf("P[%d] ",i);
for(j=0;j<rz;j++)
scanf("%d", &MAX[i][j]);
}
printf("\n");
A: d=-1;
for(i=0;i <pno;i++)
{ P[i]=i;
printf("P[%d] ",P[i]);
for(j=0;j<rz;j++)
{
scanf("%d",&allocated[i][j]);
avail[j]+=allocated[i][j];
}
}
62
Enter the allocation matrix :
P[0] 3 2 1
P[1] 1 1 2
P[2] 4 1 2
63