You are on page 1of 63

Department of Computer Science

and Engineering

Operating System Lab Manual


Academic year 2018-2019

Prepared
by

Mr.V.BALU
Assistant Professor

1
OPERATING SYSTEMS LAB MANUAL INDEX

Exp. No. Division of Experiments List of Experiments Page No


a) Ls
b) Pwd
LINUX COMMAND c) mkdir
d) cd 1-10
e) rmdir
File and Directory Related f) cat
Commands g) mv
h) rm
a) ps
1 Process and Status Information b) who 11-13
Commands c) who am i
d) date
e) echo
a) Head
Text Related Commands b) Tail 14-25
c) wc
d) find
File Permission Commands a) chmod 26-29

a) Write a Shell Program to find the


whether a Number is even or odd
b) Write a Shell Program to find the
biggest of two numbers 30-34
c) Write a Shell Program to find the
2 SHELL PROGRAMMING
biggest of three numbers
d) Write a Shell Program to find the
factorial of a Number
e) Write a Shell Program to display
Fibonacci Series
a) Grep,
3 Unix Pipes and Filters b) Sed 35-40
c) Awk commands
a) To implement Stat
b) Wait
c) Getpid 41-46
d) Opendir, readdir
4 System Calls e) Open
f) To Implement Unix I/o System calls
Open, Read, Write, etc

2
OPERATING SYSTEMS LAB MANUAL INDEX

Exp. No. Division of Experiments List of Experiments Page No


a) Fork() 47-48
5 Process Management
b) Exec()
a) FIFO
6 CPU Scheduling Algorithms b) Round Robin 49-52
c) SJF
To write a program to solve the Producer
Consumer Problem using Semaphores 53-57
7 Process Synchronization
To implement Dining Philosophers Problem
using Threads and Semaphores

Deadlock Management Write a C Program to Implement BANKER’S 58-60


8
Techniques Algorithm for deadlock avoidance

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

File and Directory Related Commands


LS - command

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 $

To go in your last directory you can use following command:

$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

/etc/passwd /users/sjones/chem/notes /dev/rdsk/Os3

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:

$mkdir docs pub


$

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:

$rmdir dirname1 dirname2 dirname3


$

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:

$mv olddir newdir


$

You can rename a directory mydir to yourdir as follows:

$mv mydir yourdir


$

The directories . (dot) and .. (dot dot)


The filename . (dot) represents the current working directory; and the filename .. (dot dot) represent
the directory one level above the current working directory, often referred to as the parent directory.
If we enter the command to show a listing of the current working directories files and use the -a option
to list all the files and the -l option provides the long listing, this is the result.

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.

1) To view a single file


Command:
$cat filename
Output
It will show content of given filename
2) To view multiple files
Command:
$cat file1 file2
Output

This will show content of file1 and file2.


3) To view contents of a file preceding with line numbers.
Command:
$cat -n filename
Output
It will show content with line number
example:-cat-n geeks.txt
1)This is geeks
2)A unique array

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

Removing more than one file at a time


$ rm b.txt c.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

Note: -f option of rm command will not work for write-protect directories.

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

Now, deletion from A directory(as parent directory) will be done as:


$ rm *

12
rm: cannot remove 'B': Is a directory
rm: cannot remove 'C': Is a directory

$ rm -r *

$ ls

Every directory and file inside A directory is deleted.

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

ps command in Linux with Examples


As we all know Linux is a multitasking and multi-user systems. So, it allows multiple processes to
operate simultaneously without interfering with each other. Process is one of the important fundamental
concept of the Linux OS. A process is an executing instance of a program and carry out different tasks
within the operating system.
Linux provides us a utility called ps for viewing information related with the processes on a system
which stands as abbreviation for “Process Status”. ps command is used to list the currently running
processes and their PIDs along with some other information depends on different options. It reads the
process information from the virtual files in /proc file-system. /proc contains virtual files, this is the
reason it’s referred as a virtual file system.
ps provides numerous options for manipulating the output according to our need.
Syntax –ps [options]
Options for ps Command :

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.

2. View all the processes except session leaders :


[root@rhel7 ~]# ps -d

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

4. View all processes associated with this terminal :


[root@rhel7 ~]# ps -T

5. View all the running processes :


[root@rhel7 ~]# ps -r

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

who command in Linux


who command is used to find out the following information :
1. Time of last system boot
2. Current run level of the system
3. List of logged in users and more.
Description : The who command is used to get information about currently logged in user on to system.

Syntax : $who [options] [filename]

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 .

 It is basically the concatenation of the strings “who”,”am”,”i” as whoami.


 It displays the username of the current user when this command is invoked.
 It is similar as running the id command with the options -un.

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

Thu Feb 28 08:30:19 MST 2019

echo command in Linux with Examples


echo command in linux is used to display line of text/string that are passed as an argument . This is a
built in command that is mostly used in shell scripts and batch files to output status text to the screen
or a file.
Syntax :

echo [option] [string]


Displaying a text/string :

Syntax :
echo [string]
Example :

echo "Unix echo command”

16
TEXT RELATED COMMANDS

Head command in Linux with examples


It is the complementary of Tail command. The head command, as the name implies, print the top N
number of data of the given input. By default it prints the first 10 lines of the specified files. If more
than one file name is provided then data from each file is precedes by its file name.
Syntax:
head [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states
and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
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 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

With using -q option


$ head -q state.txt capital.txt
Andhra Pradesh

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

Tail command in Linux with examples


It is the complementary of head command.The tail command, as the name implies, print the last N
number of data of the given input. By default it prints the last 10 lines of the specified files. If more than
one file name is provided then data from each file is precedes by its file name.
Syntax:
tail [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states
and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat

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

With positive num


$ tail -c +263 state.txt
Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
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
$ tail state.txt capital.txt
state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
capital.txt
Dispur

21
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi

With using -q option


$ tail -q state.txt capital.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West BengalDispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi
Bengaluru
4. -f: This option is mainly used by system administration to monitor the growth of the log files written
by many Unix program as they are running. This option shows the last ten lines of a file and will update
when new lines are added. As new lines are written to the log, the console will update with the new
lines. The prompt doesn’t return even after work is over so, we have to use the interrupt key to abort
this command. In general, the applications writes error messages to log files. You can use the -f option
to check for the error messages as and when they appear in the log file.
$ tail -f logfile
5. -v: By using this option, data from the specified file is always preceded by its file name.
$ tail -v state.txt
==> state.txt <==
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura

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.

wc command in Linux with examples


wc stands for word count. As the name implies, it is mainly used for counting purpose.
 It is used to find out number of lines, word count, byte and characters count in the files specified in the
file arguments.
 By default it displays four-columnar output.
 First column shows number of lines present in a file specified, second column shows number of words
present in the file, third column shows number of characters present in file and fourth column itself is the
file name which are given as argument.
Syntax:
wc [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt containing 5 names of the Indian states
and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

$ 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

With more than one file name


$ wc -l state.txt capital.txt
5 state.txt
5 capital.txt
10 total
2. -w: This option prints the number of words present in a file. With this option wc command displays
two-columnar output, 1st column shows number of words present in a file and 2nd is the file name.
With one file name
$ wc -w state.txt
7 state.txt

With more than one file name


$ wc -w state.txt capital.txt
7 state.txt
5 capital.txt
12 total
3. -c: This option displays count of bytes present in a file. With this option it display two-columnar
output, 1st column shows number of bytes present in a file and 2nd is the file name.
With one file name
$ wc -c state.txt
63 state.txt

With more than one file name


$ wc -c state.txt capital.txt
63 state.txt
45 capital.txt
108 total
4. -m: Using -m option ‘wc’ command displays count of characters from a file.
With one file name
$ wc -m state.txt
63 state.txt

With more than one file name


$ wc -m state.txt capital.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

With more than one file name


$ wc -L state.txt capital.txt
17 state.txt
10 capital.txt
17 total
6. –version: This option is used to display the version of wc which is currently running on your system.
$ wc --version
wc (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 and David MacKenzie.


Applications of wc Command
1. To count all files and folders present in directory: As we all know ls command in unix is used to
display all the files and folders present in the directory, when it is piped with wccommand with -l option
it display count of all files and folders present in current directory.
$ ls gfg
a.txt
b.txt
c.txt
d.txt
e.txt
geeksforgeeks
India

$ 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

Find command in Linux with examples


The find command in UNIX is a command line utility for walking a file hierarchy. It can be used to find
files and directories and perform subsequent operations on them. It supports searching by file, folder,
name, creation date, modification date, owner and permissions. By using the ‘-exec’ other UNIX
commands can be executed on files or folders found.
Syntax :
$ find [where to start searching from]
[expression determines what to find] [-options] [what to find]
Options :
 -exec CMD: The file being searched which meets the above criteria and returns 0 for as its exit status for
sucessful command execution.
 -ok CMD : It works same as -exec except the user is prompted first.
 -inum N : Search for files with inode number ‘N’.
 -links N : Search for files with ‘N’ links.
 -name demo : Search for files that are specified by ‘demo’.
 -newer file : Search for files that were modified/created after ‘file’.
 -perm octal : Search for the file if permission is ‘octal’.
 -print : Display the path name of the files found by using the rest of the criteria.
 -empty : Search for empty files and directories.
 -size +N/-N : Search for files of ‘N’ blocks; ‘N’ followed by ‘c’can be used to measure size in characters; ‘+N’
means size > ‘N’ blocks and ‘-N’ means size < 'N' blocks.
 -user name : Search for files owned by user name or ID ‘name’.
 \(expr \) : True if ‘expr’ is true; used for grouping criteria combined with OR or AND.
 ! expr : True if ‘expr’ is false.
Examples :
Consider the following tree hirerachy :

26
1. Search a file with specific name.
$ find ./GFG -name sample.txt
It will search for sample.txt in GFG directory.
Output :

2. Search a file with pattern.


$ find ./GFG -name *.txt
It will give all files which have ‘.txt’ at the end.
Output :

3. How to find and delete a file with confirmation.


$ find ./GFG -name sample.txt -exec rm -i {} \;
When this command is entered, a prompt will come for confirmation, if you want to delete sample.txt or
not. if you enter ‘Y/y’ it will delete the file.
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 :

5. Search for file with entered permissions.


$ find ./GFG -perm 664
This command find all the files in the GFG directory or sub-directory with the given permissions.
Output :

6. Search text within multiple files.


$ find ./ -type f -name "*.txt" -exec grep 'Geek' {} \;
This command print lines which have ‘Geek’ in them and ‘-type f’ specifies the input type is a file.
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.

The Permission Indicators:

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.

3. Execute: User with execute permissions can run a file as a program.

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.

Using chmod in Symbolic Mode:


The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode. With
symbolic permissions you can add, delete, or specify the permission set you want by using the operators
in the following table.

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:

Changing Owners and Groups:

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:

$ chown user filelist

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:

$ chown amrood testfile


$

Changes the owner of the given file to the user amrood.

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:

$ chgrp group filelist

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:

$ chgrp special testfile

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.

In this tutorial, you will learn-

Types of Shell

There are two main shells in Linux:

1. The Bourne Shell: The prompt for this shell is $ and its derivatives are listed below:

 POSIX shell also is known as sh


 Korn Shell also knew as sh
 Bourne Again SHell also knew as bash (most popular)

33
2. The C shell: The prompt for this shell is %, and its subcategories are:

 C shell also is known as csh


 Tops C shell also is known as tcsh

We will discuss bash shell based shell scripting in this tutorial.

What is Shell Scripting?

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.

Let us understand the steps in creating a Shell Script

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.

Let's create a small script -

#!/bin/sh
ls

Let's see the steps to create it -

Command 'ls' is executed when we execute the scrip sample.sh file.

34
Adding shell comments

Commenting is important in any program. In Shell programming, the syntax to add a comment is

#comment

Let understand this with an example.

What are Shell Variables?

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

Below is a small script which will use a variable.

#!/bin/sh
echo "what is your name?"
read name
echo "How do you do, $name?"
read remark
echo "I am $remark too!"

Let's understand, the steps to create and execute the script

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

Shell Programming even or odd


echo "enter the number"
read num
if [ `expr $num % 2` -eq 0 ]
then
echo "number is even"
else
echo "number is odd"
fi

Biggest of two Numbers


echo "enter the number"
read a b
if [ $a -gt $b ]
then
echo "A is big"
else
echo "B is big"
fi

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

echo "enter the number"


read n
fact=1 i=1
while [ $i -le $n ]
do
fact=`expr $i \* $fact`
i=`expr $i + 1`
done
echo "the fcatorial number of $ni is $fact”

Fibonacci series

echo " ENTER THE LIMIT FOR FIBONNACI SERIES"


read lim
n1=0 n2=1 var=0
echo "FIBONACCI SERIES IS "
echo "$n1"
echo "$n2"
while [ $var -lt `expr $lim - 2` ]
do
n3=`expr $n1 + $n2 `
n1=`expr $n2 ` n2=`expr $n3 ` var=`expr $var + 1 `
echo "$n2"
done

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:

grep [options] pattern [files]


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

The sort Command:


The sort command arranges lines of text alphabetically or numerically. The example below sorts the
lines in the food file:
$sort food
Afghani Cuisine
Bangkok Wok
Big Apple Deli
Isle of Java
Mandalay
Sushi and Sashimi
Sweet Tooth
Tio Pepe's Peppers
38
$
The sort command arranges lines of text alphabetically by default. There are many options that control
the sorting:

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.

1.> sed 's/unix/linux/' file.txt

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.

4. > sed 's/unix/linux/3g' file.txt

OUTPUT :
unix is great os. unix is opensource. linux is free os.
learn operating system.
unixlinux which one you choose.

5. > sed 's/unix/linux/p' file.txt

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.

8. >grep 'unix' file.txt


OUTPUT :
Sed as grep command.

9. >sed -n '/unix/ p' file.txt


OUTPUT :
Sed as grep command.

10. >sed '/unix/ a "Add a new line"' file.txt


OUTPUT :
"Add a new line"
unix is great os. unix is opensource. unix is free os.
learn operating system.
"Add a new line"
unixlinux which one you choose.

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.

create employee.txt file which has the following content


$vi employee.txt
‘Insert’
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

$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

1. Default behavior of Awk

By default Awk prints every line from the file.


$ awk '{print;}' 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

2. Print the lines which matches with the pattern.


$ awk '/Thomas/
> /Nisha/' employee.txt
100 Thomas Manager Sales $5,000
400 Nisha Manager Marketing $9,500

3. Print only specific field.


$ awk '{print $2,$5;}' employee.txt
Thomas $5,000
Jason $5,500
Sanjay $7,000

42
Nisha $9,500
Randy $6,000

$ awk '{print $2,$NF;}' employee.txt


Thomas $5,000
Jason $5,500
Sanjay $7,000
Nisha $9,500
Randy $6,000

4. Initialization and Final Action


Awk has two important patterns which are specified by the keyword called BEGIN and END.
Syntax:
BEGIN { Actions}
{ACTION} # Action for everyline in a file
END { Actions }
$ awk 'BEGIN {print "Name\tDesignation\tDepartment\tSalary";}
> {print $2,"\t",$3,"\t",$4,"\t",$NF;}
> END{print "Report Generated\n--------------";
> }' employee.txt

Name Designation Department Salary


Thomas Manager Sales $5,000
Jason Developer Technology $5,500
Sanjay Sysadmin Technology $7,000
Nisha Manager Marketing $9,500
Randy DBA Technology $6,000
Report Generated

5. Find the employees who has employee id greater than 200


$ awk '$1 >200' employee.txt
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000

6. Print the list of employees in Technology department


$ awk '$4 ~/Technology/' employee.txt
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
500 Randy DBA Technology $6,000

7. Print number of employees in Technology department


$ awk 'BEGIN { count=0;}
$4 ~ /Technology/ { count++; }
END { print "Number of employees in Technology Dept =",count;}' employee.txt
Number of employees in Technology Dept = 3

43
4. SYSTEM CALLS

SYSTEM CALLS OF UNIX OPERATING SYSTEM(STAT())

AIM :

To Execute a Unix Command in a ‘C’ program using stat() system call.

ALGORITHM:

1. Start the program


2. Declare the variables for the structure stat
3. Allocate the size for the file by using malloc function
4. Get the input of the file whose statistics want to be founded
5. Repeat the above step until statistics of the files are listed
6. Stop the program.

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:

enter name of file whose stsistics has to stat.c user id 621


block size :4096
last access time 1145148485
time of last modification 1145148485 porduction mode 33204
size of file 654 number of links:1

44
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(WAIT())

AIM :

To Execute a Unix Command in a ‘C’ program using wait() system call.

ALGORITHM :

1. Start the program


2. Initialize the necessary variables
3. Use wait() to return the parent id of the child else return -1 for an error.
4. Stop the program.

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:

1. Start the program


2. Declare the necessary variables
3. The getpid() system call returns the process ID of the parent of the calling process
4. Stop the program.

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)

AIM : To write a C program to display the files in the given directory

ALGORITHM:

1. Start the program


2. Create a directory “os lab” with it having one .c and one .txt file for the search. Change the
control from cd.
3. 3. Declare the variable to the structure dirent (defines the file system-independent
directory)and also for DIR
4. Specify the directory path to be displayed using the opendir system call
5. Check for the existence of the directory and read the contents of the directory using readdir
system call (returns a pointer to the next active directory entry)
6. Repeat the above step until all the files in the directory are listed
7. Stop the program

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:

Enter directory name


oslab
openreaddir.c
a.out
..vidhya.c
Vidhya

47
4. SYSTEM CALLS OF UNIX OPERATING SYSTEM(OPEN())

AIM : To Execute a Unix Command in a ‘C’ program using open() system call.

ALGORITHM :

1. Start the program


2. Declare the necessary variables
3. Open file1.dat to read or write access
4. Create file1.dat if it doesn’t exist
5. Return error if file already exist
6. Permit read or write access to the file
7. Stop the program.

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:

file1.dat opened for read/write access.


file1.dat is currently empty

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:

To create a process in the following hierarchy

ALGORITHM:

1. Start the program.


2. Declare the necessary variables.
3. Parent process is the process of the program which is running.
4. Create the child1 process using fork() When parent is active.
5. Create the child2 process using fork() when child1 is active.
6. Create the child3 process using fork() when child2 is active.
7. Stop the program.

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:

1. Start the program


2. Declare the necessary variables
3. Use the prototype execv (filename,argv) to transform an executable binary file into process
4. Repeat this until all executed files are displayed
5. Stop the program.

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

FIFO (FIRST –IN FIRST -OUT) CPU SCHEDULING

AIM:

To write a program to implement the FIFO (FIRST –IN FIRST -OUT) CPU scheduling Algorithm

ALGORITHM:

1. START the program


2. Get the number of processors
3. Get the Burst time of each processors
4. Calculation of Turn Around Time and Waiting Time a) tot_TAT = tot_TAT + pre_TAT
b) avg_TAT = tot_TAT/num_of_proc
c) tot_WT = tot_WT + pre_WT + PRE_BT
d) avg_WT = tot_WT/num_of_proc
5. Display the result
6. STOP the program

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:

Enter The No Of Process :3


Enter The Burst Time (in ms) For Process # 1 :10
Enter The Burst Time (in ms) For Process # 2 :30
Enter The Burst Time (in ms) For Process # 3 :20

Process Waiting Time TurnAround Time


(in ms) (in ms)
Process # 1 0 10
Process # 2 10 40
Process # 3 40 60

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:

To write a program to implement the Round Robin CPU scheduling Algorithm

ALGORITHM:

1. START the program


2. Get the number of processors
3. Get the Burst time(BT) of each processors
4. Get the Quantum time(QT)
5. Execute each processor until reach the QT or BT
6. Time of reaching processor’s BT is it’s Turn Around Time(TAT)
7. Time waits to start the execution, is the waiting time(WT) of each processor
8. Calculation of Turn Around Time and Waiting Time m) tot_TAT = tot_TAT + cur_TAT
n) avg_TAT = tot_TAT/num_of_proc o) tot_WT = tot_WT + cur_WT
p) avg_WT = tot_WT/num_of_proc
9. Display the result
10. STOP the program

PROGRAM: (Round Robin 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();
}

OUTPUT: (Round Robin Scheduling Algorithm)

55
7. PROCESS SYNCHRONIZATION

AIM :

To write a program to solve the Producer Consumer Problem using Semaphores

ALGORTIHM :

1. START the program


2. If the request is for Producer
a. Get the count of number of items to be produced b. Add the count with current Buffer size
c. If the new Buffer size is full
Don’t produce anything; display an error message
Producer has to wait till any consumer consume the existing item d. Else
Produce the item
Increment the Buffer by the number of item produced
3. If the request is for Consumer
a. Get the count of number of items to be consumed b. Subtract the count with current
Buffer size
c. If the new Buffer size is lesser than or equal to 0
Don’t allow the consumer to consume anything; display an error message
Consumer has to wait till the producer produce new items
d. Else
Consume the item
Decrement the Buffer by the number of item consumed
4. STOP the program

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

DINING PHILOSOPHERS PROBLEM USING SEMAPHORES

AIM: To implement Dining Philosophers Problem using Threads and Semaphores

ALGORITHM:

1. Define the number of philosophers


2. Declare one thread per philosopher
3. Declare one semaphore (represent chopsticks) per philosopher
4. When a philosopher is hungry
1. See if chopsticks on both sides are free
2. Acquire both chopsticks or eat
3. restore the chopsticks
4. If chopsticks aren’t free
5. Wait till they are available

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

RESULT: THUS THE PROGRAM WAS SUCESSFULLY EXECUTED.

60
8. DEADLOCK MANAGEMENT TECHNIQUES

BANKERS ALGORITHM

AIM: To implement Banker’s Algorithm IN UNIX using ‘C’ .

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];
}
}

printf("\nEnter the MAX matrix \n ");


for(i=0;i<rz;i++)
{ printf(" %c",(i+97));
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;
printf(">");
getch();
}
OUTPUT :
Enter the number of resources ; 3
Enter the maximum instance of each resource :
a=10
b=7
c=7
Enter the number of processes : 3

62
Enter the allocation matrix :
P[0] 3 2 1
P[1] 1 1 2
P[2] 4 1 2

Enter the max matrix ;


P[0] 4 4 4
P[1] 3 4 5
P[2] 5 2 4
< P[2] P[0] P[1] >

63

You might also like