Top Banner
Prepared By |Mr. Neelamani Samal 1 OPERATING STSTEM LAB MANUAL (For 6 th sem CSE & IT) Strictly According To BPUT Syllabus Prepared By : Mr.Neelamani Samal
47

Os lab manual

Nov 20, 2014

Download

Education

Neelamani Samal

This Operating System lab manual is designed strictly according to BPUT Syllabus.Any suggestions or comments are well come at [email protected]
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Os lab manual

Prepared By |Mr. Neelamani Samal 1

OPERATING STSTEM LAB MANUAL

(For 6th

sem CSE & IT)

Strictly According To BPUT Syllabus

Prepared By : Mr.Neelamani Samal

Page 2: Os lab manual

Prepared By |Mr. Neelamani Samal 2

CONTENT

Experiment

No. Name of The Experiment Page

NO.

1 Basic UNIX Commands. 3

2 UNIX Shell Programming. 22

3 Programs on process creation and synchronization,

inter process communication. 39

4 Programs on UNIX System calls. 45

Page 3: Os lab manual

Prepared By |Mr. Neelamani Samal 3

Laboratory Experiment 1

Objective :-

To learn some basic UNIX commands to do system level programming.

Software Required :-

UNIX Operating System

Commands:-

Folder/Directory Commands and Options

Action UNIX options &

filespec

DOS filespec &

options

Check

current Print Working Directory

pwd cd

Return to user's home folder cd

cd ~

cd /

Up one folder cd ..

Make directory mkdir proj1

Remove empty directory rmdir /usr/sam rmdir

or rd

Remove directory -recursively rm -r rmdir

/s (NT)

deltree (Win

95)

Page 4: Os lab manual

Prepared By |Mr. Neelamani Samal 4

File Listing Commands and Options

Action UNIX options &

filespec

DOS filespec &

options

List directory tree -recursively ls -r tree

List last access dates of files, with hidden

files

ls -l -a

List files by reverse date ls -t -r *.* dir *.exe

/o-d

List files verbosely by size of file ls -l -s *.* dir *.* /v

/os

List files recursively including contents

of other directories

ls -R *.* dir *.* /s

List number of lines in folder wc -l *.xtuml

sed -n '$='

sed -n "$="

List files with x anywhere in the name ls | grep x

File Manipulation Commands and Options

Action UNIX options &

filespec

DOS filespec &

options

Create new (blank) file touch afilename

Copy old.file to new.file

-p preserve file attributes (e.g.

ownership and edit dates)

-r copy recursively through

directory structure

-a archive, combines the flags -p -

R and -d

cp old.file new.file

copy old.file

new.*

Move old.file (-i interactive flag

prompts before overwriting files)

mv -i old.file /tmp

Copy old.file

/tmp del old.file

Remove file (-intention) rm -i sam.txt del sam.txt

Compare two files and show

differences

diff comp

fc

Page 5: Os lab manual

Prepared By |Mr. Neelamani Samal 5

File Utilities

Action UNIX options & filespec

DOS filespec &

options

View a file vi file.txt edit file.txt

Edit file pico myfile edit myfile

Concatenate files cat file1 file2 to

standard output. copy file2

>>file1

Counts -lines, -words, and -

characters in a file wc -l

Displays line-by-line differences

between pairs of text files.

diff

calculator bc

calendar for September, 1752

(when leap years began) cal 9 1752

Pattern Matching

Pattern Example

Position ? stands for any single character ls ?1

Position * stands for any number of

characters

ls 2*

Specific

characters [AB] stands for any number of

characters

ls [AB]1 would yield A1

and B1

Range of

characters [A-Z] stands for letters from A

thru Z

Page 6: Os lab manual

Prepared By |Mr. Neelamani Samal 6

Files

ls --- lists your files

ls -l --- lists your files in 'long format', which

contains lots of useful information, e.g. the exact size of the file, who

owns the file and who has the right to look at it, and when it was last

modified.

ls -a --- lists all files, including the ones whose

filenames begin in a dot, which you do not always want to see.

There are many more options, for example to list files by size, by date,

recursively etc.

more filename --- shows the first part of a file, just as much as

will fit on one screen. Just hit the space bar to see more or q to quit. You

can use /pattern to search for a pattern.

mv fname1 fname2 --- moves a file (i.e. gives it a different name, or

moves it into a different directory (see below)

cp fname1 fname2 --- copies a file

rm filename --- removes a file. It is wise to use the option rm -

i, which will ask you for confirmation before actually deleting anything.

You can make this your default by making an alias in your .cshrc file.

diff fname1 fname2 --- compares files, and shows where they differ

wc fname --- tells you how many lines, words, and

characters there are in a file

chmod opt fname --- lets you change the read, write, and execute

permissions on your files. The default is that only you can look at them

and change them, but you may sometimes want to change these

permissions. For example, chmod o+r filename will make the file

readable for everyone, and chmod o-rfilename will make it unreadable

for others again. Note that for someone to be able to actually look at the

file the directories it is in need to be at least executable.

Page 7: Os lab manual

Prepared By |Mr. Neelamani Samal 7

Directories

Directories, like folders on a Macintosh, are used to group files together in a

hierarchical structure.

mkdir dirname --- make a new directory

cd dirname --- change directory. You basically 'go' to another

directory, and you will see the files in that directory when you do 'ls'.

You always start out in your 'home directory', and you can get back there

by typing 'cd' without arguments. 'cd ..' will get you one level up from

your current position. You don't have to walk along step by step - you

can make big leaps or avoid walking around by specifying pathnames.

pwd --- tells you where you currently are.

Finding things

ff --- find files anywhere on the system. This can be

extremely useful if you've forgotten in which directory you put a file, but

do remember the name. In fact, if you use ff -p you don't even need the

full name, just the beginning. This can also be useful for finding other

things on the system, e.g. documentation.

grep string fname(s) --- looks for the string in the files. This can be

useful a lot of purposes, e.g. finding the right file among many, figuring

out which is the right version of something, and even doing serious

corpus work. grep comes in several varieties (grep, egrep, and fgrep)

and has a lot of very flexible options. Check out the man pages if this

sounds good to you.

Page 8: Os lab manual

Prepared By |Mr. Neelamani Samal 8

About other people

w --- Tells you who's logged in, and what they're doing.

Especially useful: the 'idle' part. This allows you to see whether they're

actually sitting there typing away at their keyboards right at the moment.

who --- Tells you who's logged on, and where they're coming

from. Useful if you're looking for someone who's actually physically in

the same building as you, or in some other particular location.

finger username --- gives you lots of information about that user, e.g.

when they last read their mail and whether they're logged in. Often

people put other practical information, such as phone numbers and

addresses, in a file called .plan. This information is also displayed by

'finger'.

last -1 username --- tells you when the user last logged on and off

and from where. Without any options, last will give you a list of

everyone's logins.

talk username --- lets you have a (typed) conversation with

another user

write username --- lets you exchange one-line messages with

another user

elm --- lets you send e-mail messages to people around the world (and, of

course, read them). It's not the only mailer you can use, but the one we

recommend. About your (electronic) self

whoami --- returns your username. Sounds useless, but isn't.

You may need to find out who it is who forgot to log out somewhere,

and make sure *you* have logged out.

passwd --- lets you change your password, which you should

do regularly.

ps -u yourusername --- lists your processes. Contains lots of

information about them, including the process ID, this list will contain

the processes you need to kill.

kill PID --- kills (ends) the processes with the ID you

gave. This works only for your own processes, of course. Get the ID by

using ps. If the process doesn't 'die' properly, use the option -9. But

attempt without that option first, because it doesn't give the process a

chance to finish possibly important business before dying. You may

need to kill processes for example if your modem connection was

interrupted and you didn't get logged out properly, which sometimes

happens.

Page 9: Os lab manual

Prepared By |Mr. Neelamani Samal 9

quota -v --- show what your disk quota is (i.e. how much

space you have to store files), how much you're actually using, and in

case you've exceeded your quota (which you'll be given an automatic

warning about by the system) how much time you have left to sort them

out (by deleting )

du filename --- shows the disk usage of the files and

directories in filename (without argument the current directory is

used). du -s gives only a total.

last yourusername --- lists your last logins.

Login and authentication

login access computer; start interactive session

logout disconnect terminal session

passwd change local login password; you must set a strong password that is

not easily guessed

Information

date show date and time

history list of previously executed commands

man show online documentation by program name

w, who who is on the system and what they are doing

whoami who is logged onto this terminal

File management

Page 10: Os lab manual

Prepared By |Mr. Neelamani Samal 10

cat combine files

cp copy files

ls list files in a directory and their attributes

mv change file name or directory location

rm remove files

ln create another link (name) to a file

chmod set file permissions

Display contents of files

cat copy files to display device

more show text file on display terminal with paging control

head show first few lines of a file(s)

tail show last few lines of a file; or reverse line order

vi full-featured screen editor for modifying text files

pico simple screen editor for modifying text files

grep display lines that match a pattern

lpr send file to printer

diff compare two files and show differences

cmp compare two binary files and report if different

comm compare two files; show common or unique lines

wc count characters, words, and lines in a file

Page 11: Os lab manual

Prepared By |Mr. Neelamani Samal 11

Directories

cd change to new directory

mkdir create new directory

rmdir remove empty directory (you must remove files first)

mv change name of directory

pwd show current directory

Disks

df summarize free space on disk filesystems

du show disk space used by files or directories

Controlling program execution for C-shell

& run job in background

^c kill job in foreground

^z suspend job in foreground

fg restart suspended job in foreground

bg run suspended job in background

; delimit commands on same line

() group commands on same line

! re-run earlier commands from history list

jobs list current jobs

Page 12: Os lab manual

Prepared By |Mr. Neelamani Samal 12

ps show process information

kill kill background job or previous process

nice run program at lower priority

at run program at a later time

crontab run program at specified intervals

limit see or set resource limits for programs

alias create alias name for program (normally used in .login file)

sh, csh execute command file

Controlling program input/output for C-shell

| pipe output to input

> redirect output to a storage file

< redirect input from a storage file

>> append redirected output to a storage file

tee copy input to both file and next program in pipe

script make file record of all terminal activity

Editors and formatting utilities

sed programmable text editor for data streams

vi full-featured editor for character terminals

pico very simple text editor

Page 13: Os lab manual

Prepared By |Mr. Neelamani Samal 13

Printing (BSD based)

lpr send file to print queue

lpq examine status of files in print queue

lprm remove a file from print queue

enscript convert text files to PostScript format for printing

Starting and Ending

login: `Logging in'

ssh: Connect to another machine

logout: `Logging out'

File Management

emacs: `Using the emacs text editor'

mkdir: `Creating a directory'

cd: `Changing your current working directory'

ls: `Finding out what files you have'

cp: `Making a copy of a file'

mv: `Changing the name of a file'

rm: `Getting rid of unwanted files'

chmod: `Controlling access to your files'

cmp: Comparing two files

wc: Word, line, and character count

compress: Compress a file

Communication

e-mail: `Sending and receiving electronic mail'

talk: Talk to another user

Page 14: Os lab manual

Prepared By |Mr. Neelamani Samal 14

write: Write messages to another user

sftp: Secure file transfer protocol

Information

man: Manual pages

quota -v: Finding out your available disk space quota

ical: `Using the Ical personal organizer'

finger: Getting information about a user

passwd: Changing your password

who: Finding out who's logged on

Printing

lpr: `Printing'

lprm: Removing a print job

lpq: Checking the print queues

Job control

ps: `Finding your processes'

kill: `Killing a process'

nohup: Continuing a job after logout

nice: Changing the priority of a job

&: `What is a background process?'

Cntrl-z: Suspending a process

fg: `Resuming a suspended process'

Banner command.

banner prints characters in a sort of ascii art poster, for example to print wait in

big letters. I will type

banner wait at unix command line or in my script. This is how it will look.

Page 15: Os lab manual

Prepared By |Mr. Neelamani Samal 15

# # ## # #####

# # # # # #

# # # # # #

# ## # ###### # #

## ## # # # #

# # # # # #

Cal command

cal command will print the calander on current month by default. If you want to

print calander of august of 1965. That's eightht month of 1965.

cal 8 1965 will print following results.

August 1965

S M Tu W Th F S

1 2 3 4 5 6 7

8 9 10 11 12 13 14

15 16 17 18 19 20 21

22 23 24 25 26 27 28

29 30 31

Clear command

clear command clears the screen and puts cursor at beginning of first line.

Calendar command

calendar command reads your calendar file and displays only lines with current

day.

File Management commands.

cat,cd, cp, file,head,tail, ln,ls,mkdir ,more,mv, pwd, rcp,rm, rmdir, wc.

Pwd command.

pwd command will print your home directory on screen, pwd means print

working directory.

/u0/ssb/sandeep

is output for the command when I use pwd in /u0/ssb/sandeep directory.

Page 16: Os lab manual

Prepared By |Mr. Neelamani Samal 16

Ls command

ls command is most widely used command and it displays the contents of

directory.

options

ls will list all the files in your home directory, this command has many

options.

ls -l will list all the file names, permissions, group, etc in long format.

ls -a will list all the files including hidden files that start with . .

ls -lt will list all files names based on the time of creation, newer files

bring first.

ls -Fxwill list files and directory names will be followed by slash.

ls -Rwill lists all the files and files in the all the directories, recursively.

ls -R | more will list all the files and files in all the directories, one page

at a time.

Mkdir command.

mkdir sandeep will create new directory, i.e. here sandeep directory is created.

Cd command.

cd sandeep will change directory from current directory to sandeep directory.

Use pwd to check your current directory and ls to see if sandeep directory is

there or not.

You can then use cd sandeep to change the directory to this new directory.

will restore all files whose name contain "save"

find . -depth -print | cpio -padm /mydir will move a directory tree.

Chmod command.

chmod command is used to change permissions on a file.

Page 17: Os lab manual

Prepared By |Mr. Neelamani Samal 17

for example if I have a text file with calender in it called

cal.txt.

initially when this file will be created the permissions for this file depends

upon umask set in your profile files. As you can see this file has

666 or -rw-rw-rw attributes.

ls -la cal.txt

-rw-rw-rw- 1 ssb dxidev 135 Dec 3 16:14 cal.txt

In this line above I have -rw-rw-rw- meaning respectively that owner can read

and write file, member of the owner's group can read and write this file

and anyone else connected to this system can read and write this file., next

ssb is owner of this file dxidev is the group of this file, there are 135 bytes

in this file, this file was created on December 3 at time16:14 and at the end

there is name of this file. Learn to read these permissions in binary, like this

for example Decimal 644 which is 110 100 100 in binary meand rw-r--r-- or

user can read,write this file, group can read only, everyone else can read only.

Similarly, if permissions are 755 or 111 101 101 that means rwxr-xr-x or user

can read, write and execute, group can read and execute, everyone else can read

and execute. All directories have d in front of permissions. So if you don't want

anyone to see your files or to do anything with it use chmod command and

make permissions so that only you can read and write to that file, i.e.

chmod 600 filename.

Date command.

Date displays todays date, to use it type date at prompt.

Sun Dec 7 14:23:08 EST 1997

is similar to what you should see on screen.

Df command.

df command displays information about mounted filesystems. It reports the

number of free disk blocks. Typically a Disk block is 512 bytes (or 1/2

Kilobyte).

syntax is

Page 18: Os lab manual

Prepared By |Mr. Neelamani Samal 18

df options name

Options

-b will print only the number of free blocks.

-e will print only the number of free files.

-f will report free blocks but not free inodes.

-F type will report on an umounted file system specified by type.

-k will print allocation in kilobytes.

-l will report only on local file systems.

-n will print only the file system name type, with no arguments it lists

type of all filesystems

Du command.

du command displays disk usage.

Env command.

env command displays all the variables.

Finger command.

finger command.

PS command

ps command is probably the most useful command for systems administrators.

It reports information on active processes.

ps options

options.

-a Lists all processes in system except processes not attached to

terminals.

-e Lists all processes in system.

-f Lists a full listing.

-j print process group ID and session ID.

Page 19: Os lab manual

Prepared By |Mr. Neelamani Samal 19

Shutdown command.

Shutdown command can only be executed by root. To gracefully bring down a

system, shutdown command is used.

options.

-gn use a grace-period of n seconds (default is 60).

-ik tell the init command to place system in a state k.

o s single-user state (default)

o 0 shutdown for power-off.

o 1 like s, but mount multi-user file systems.

o 5 stop system, go to firmware mode.

o 6 stop system then reboot.

-y suppress the default prompt for confirmation.

Who command

who command displays information about the current status of system.

who options file

Who as default prints login names of users currently logged in.

Options

-a use all options.

-b Report information about last reboot.

-d report expired processes.

-H print headings.

-p report previously spawned processes.

-u report terminal usage.

date to display the current date and time

kill to kill (or destroy) the process with a given pid (process identification

Page 20: Os lab manual

Prepared By |Mr. Neelamani Samal 20

number) as argument

logout to log out from the Unix system

man to get information on a Unix command;

to look up the page in the online manual for that command

man CC shows the pages of the Unix manual referring

to the C++ compiler (CC) on the screen.

nslookup to find the address of a given machine

nslookup yourmach returns the name and address of the

machine yourmach, along with the name and

address of its server.

passwd to change your current password

printenv to show the current environment setting

ps to list your current processes by their pid (process identification number)

setenv to change an environment setting

setenv DISPLAY yourmach:0 tells the Xserver that the Xterminal

named yourmach is where any windows

created are to be displayed.

setenv PRINTER xxx makes xxx be the default printer for

any lpr or enscript commands.

source to reexecute a source shell script file

source .login

re-executes your .login file

(normally executed when you log in);

useful after making changes to the .login file

(removing the need to exit and re-login);

time to time the execution of a given command

time anyunixcommand executes anyunixcommand and returns the

user, system, and total time taken for the

execution

Who to list the users currently logged in to given machine;

to find out who is logged in

Page 21: Os lab manual

Prepared By |Mr. Neelamani Samal 21

Whoami to display login of user currently logged onto given terminal;

to answer the question: "Who am I?"

Other Language Commands:

These commands help you to compile and debug programs in other

programming languages.

cc to compile a C program

cc -O acprog.c -o acprog -lm

compiles with optimization (-O) the C program

named acprog.c into the executable file

named acprog, allowing the compilation to

access the math library (-lm).

CC to compile a C++ program

CC -O acprog.C -o acprog -lm

compiles with optimization (-O) the C++

program named acprog.C into the executable

file named acprog, allowing the compilation to

access the math library (-lm).

dbx to debug a program

dbx aprog runs the executable program named aprog that

was compiled with a -g option in a debugging

environment.

lint to check the syntax of a C program

f77 to compile a Fortran program

f77 -c fprog.f ftn1.f ftn2.f

compiles, without generating an executable file

(-c), the Fortran program named fprog.f with

the additional Fortran

modules, ftn1.f and ftn2.f.

f77 -g -o debug anfprog.f

compiles the Fortran program

called anfprog.f with a symbol table (-g) so

that the executable file named debug can be

used with the dbx command.

Conclusion :-

Page 22: Os lab manual

Prepared By |Mr. Neelamani Samal 22

Laboratory Experiment : 2

Objective :-

To learn the basic shell program and gain knowledge about the scripting language.

Theory :-

Shell scripting

Loops Most languages have the concept of loops: If we want to repeat a task twenty times, we don't

want to have to type in the code twenty times, with maybe a slight change each time.

As a result, we have for and while loops in the Bourne shell. This is somewhat fewer features

than other languages, but nobody claimed that shell programming has the power of C.

For Loops

for loops iterate through a set of values until the list is exhausted:

for.sh

#!/bin/sh

for i in 1 2 3 4 5

do

echo "Looping ... number $i"

done

Try this code and see what it does. Note that the values can be anything at all:

for2.sh

#!/bin/sh

for i in hello 1 * 2 goodbye

do

echo "Looping ... i is set to $i"

done

Page 23: Os lab manual

Prepared By |Mr. Neelamani Samal 23

is well worth trying. Make sure that you understand what is happening here. Try it without

the * and grasp the idea, then re-read the Wildcards section and try it again with the * in place.

Try it also in different directories, and with the *surrounded by double quotes, and try it preceded

by a backslash (\*)

In case you don't have access to a shell at the moment (it is very useful to have a shell to hand

whilst reading this tutorial), the results of the above two scripts are:

Looping .... number 1

Looping .... number 2

Looping .... number 3

Looping .... number 4

Looping .... number 5

and, for the second example:

Looping ... i is set to hello

Looping ... i is set to 1

Looping ... i is set to (name of first file in current directory)

... etc ...

Looping ... i is set to (name of last file in current directory)

Looping ... i is set to 2

Looping ... i is set to goodbye

So, as you can see, for simply loops through whatever input it is given, until it runs out of input.

While Loops

while loops can be much more fun! (depending on your idea of fun, and how often you get out

of the house... )

while.sh

#!/bin/sh

INPUT_STRING=hello

while [ "$INPUT_STRING" != "bye" ]

do

echo "Please type something in (bye to quit)"

read INPUT_STRING

echo "You typed: $INPUT_STRING"

done

Page 24: Os lab manual

Prepared By |Mr. Neelamani Samal 24

Test

Test is used by virtually every shell script written. It may not seem that way, because test is not

often called directly.test is more frequently called as [. [ is a symbolic link to test, just to make

shell programs more readable. If is also normally a shell builtin (which means that the shell itself

will interpret [ as meaning test, even if your Unix environment is set up differently):

$ type [

[ is a shell builtin

$ which [

/usr/bin/[

$ ls -l /usr/bin/[

lrwxrwxrwx 1 root root 4 Mar 27 2000 /usr/bin/[ -> test

This means that '[' is actually a program, just like ls and other programs, so it must be

surrounded by spaces:

if [$foo == "bar" ]

will not work; it is interpreted as if test$foo == "bar" ], which is a ']' without a beginning

'['. Put spaces around all your operators I've highlighted the mandatory spaces with the word

'SPACE' - replace 'SPACE' with an actual space; if there isn't a space there, it won't work:

if SPACE [ SPACE "$foo" SPACE == SPACE "bar" SPACE ]

Test is a simple but powerful comparison utility. For full details, run man test on your system,

but here are some usages and typical examples.

Test is most often invoked indirectly via the if and while statements. It is also the reason you

will come into difficulties if you create a program called test and try to run it, as this shell builtin

will be called instead of your program!

The syntax for if...then...else... is:

if [ ... ]

then

# if-code

else

# else-code

fi

Note that fi is if backwards! This is used again later with case and esac.

Also, be aware of the syntax - the "if [ ... ]" and the "then" commands must be on different lines.

Alternatively, the semicolon ";" can separate them:

Page 25: Os lab manual

Prepared By |Mr. Neelamani Samal 25

if [ ... ]; then

# do something

fi

You can also use the elif, like this:

if [ something ]; then

echo "Something"

elif [ something_else ]; then

echo "Something else"

else

echo "None of the above"

fi

This will echo "Something" if the [ something ] test succeeds, otherwise it will test [

something_else ], and echo "Something else" if that succeeds. If all else fails, it will echo

"None of the above".

Try the following code snippet, before running it set the variable X to various values (try -1, 0, 1,

hello, bye, etc). You can do this as follows

$ X=5

$ export X

$ ./test.sh

... output of test.sh ...

$ X=hello

$ ./test.sh

... output of test.sh ...

$ X=test.sh

$ ./test.sh

... output of test.sh ...

Then try it again, with $X as the name of an existing file, such as /etc/hosts.

test.sh

#!/bin/sh

if [ "$X" -lt "0" ]

then

echo "X is less than zero"

fi

if [ "$X" -gt "0" ]; then

echo "X is more than zero"

fi

Page 26: Os lab manual

Prepared By |Mr. Neelamani Samal 26

[ "$X" -le "0" ] && \

echo "X is less than or equal to zero"

[ "$X" -ge "0" ] && \

echo "X is more than or equal to zero"

[ "$X" = "0" ] && \

echo "X is the string or number \"0\""

[ "$X" = "hello" ] && \

echo "X matches the string \"hello\""

[ "$X" != "hello" ] && \

echo "X is not the string \"hello\""

[ -n "$X" ] && \

echo "X is of nonzero length"

[ -f "$X" ] && \

echo "X is the path of a real file" || \

echo "No such file: $X"

[ -x "$X" ] && \

echo "X is the path of an executable file"

[ "$X" -nt "/etc/passwd" ] && \

echo "X is a file which is newer than /etc/passwd"

Note that we can use the semicolon (;) to join two lines together. This is often done to save a bit

of space in simple ifstatements. The backslash simply tells the shell that this is not the end of

the line, but the two (or more) lines should be treated as one. This is useful for readability. It is

customary to indent the following line.

As we see from these examples, test can perform many tests on numbers, strings, and

filenames.

Thanks to Aaron for pointing out that -a, -e (both meaning "file exists"), -S (file is a Socket), -

nt (file is newer than), -ot(file is older than), -ef (paths refer to the same file) and -O (file is

owned my user), are not available in the traditional Bourne shell (eg, /bin/sh on Solaris, AIX,

HPUX, etc).

There is a simpler way of writing if statements: The && and || commands give code to run if

the result is true.

#!/bin/sh

[ $X -ne 0 ] && echo "X isn't zero" || echo "X is zero"

[ -f $X ] && echo "X is a file" || echo "X is not a file"

[ -n $X ] && echo "X is of non-zero length" || \

echo "X is of zero length"

Page 27: Os lab manual

Prepared By |Mr. Neelamani Samal 27

This syntax is possible because there is a file (or shell-builtin) called [ which is linked to test.

Be careful using this construct, though, as overuse can lead to very hard-to-read code.

The if...then...else... structure is much more readable. Use of the [...] construct is

recommended for while loops and trivial sanity checks with which you do not want to overly

distract the reader.

Note that when you set X to a non-numeric value, the first few comparisons result in the

message:

test.sh: [: integer expression expected before -lt

test.sh: [: integer expression expected before -gt

test.sh: [: integer expression expected before -le

test.sh: [: integer expression expected before -ge

This is because the -lt, -gt, -le, -ge, comparisons are only designed for integers, and do not work

on strings. The string comparisons, such as != will happily treat "5" as a string, but there is no

sensible way of treating "Hello" as an integer, so the integer comparisons complain.

If you want your shell script to behave more gracefully, you will have to check the contents of the

variable before you test it - maybe something like this:

echo -en "Please guess the magic number: "

read X

echo $X | grep "[^0-9]" > /dev/null 2>&1

if [ "$?" -eq "0" ]; then

# If the grep found something other than 0-9

# then it's not an integer.

echo "Sorry, wanted a number"

else

# The grep found only 0-9, so it's an integer.

# We can safely do a test on it.

if [ "$X" == "7" ]; then

echo "You entered the magic number!"

fi

fi

In this way you can echo a more meaningful message to the user, and exit gracefully.

The $? variable is explained inVariables - Part II, and grep is a complicated beast, so here

goes: grep [0-9] finds lines of text which contain digits (0-9) and possibly other characters, so

the caret (^) in grep [^0-9] finds only those lines which don't consist only of numbers. We can

then take the opposite (by acting on failure, not success). Okay? The >/dev/null 2>&1 directs

any output or errors to the special "null" device, instead of going to the user's screen.

Many thanks to Paul Schermerhorn for correcting me - this page used to claim that grep -v

[0-9] would work, but this is clearly far too simplistic.

We can use test in while loops as follows:

Page 28: Os lab manual

Prepared By |Mr. Neelamani Samal 28

test2.sh

#!/bin/sh

X=0

while [ -n "$X" ]

do

echo "Enter some text (RETURN to quit)"

read X

echo "You said: $X"

done

This code will keep asking for input until you hit RETURN (X is zero length). Thanks to Justin

Heath for pointing out that the script didn't work - I'd missed out the quotes around $X in

the while [ -n "$X" ]. Without those quotes, there is nothing to test when $X is empty.

Alexander Weber has pointed out that running this script will end untidily:

$ ./test2.sh

Enter some text (RETURN to quit)

fred

You said: fred

Enter some text (RETURN to quit)

wilma

You said: wilma

Enter some text (RETURN to quit)

You said:

$

This can be tidied up with another test within the loop:

#!/bin/sh

X=0

while [ -n "$X" ]

do

echo "Enter some text (RETURN to quit)"

read X

if [ -n "$X" ]; then

echo "You said: $X"

fi

done

Note also that I've used two different syntaxes for if statements on this page. These are:

Page 29: Os lab manual

Prepared By |Mr. Neelamani Samal 29

if [ "$X" -lt "0" ]

then

echo "X is less than zero"

fi

.......... and ........

if [ ! -n "$X" ]; then

echo "You said: $X"

fi

You must have a break between the if statement and the then construct. This can be a

semicolon or a newline, it doesn't matter which, but there must be one or the other between

the if and the then. It would be nice to just say:

if [ ! -n "$X" ]

echo "You said: $X"

Case The case statement saves going through a whole set of if .. then .. else statements. Its

syntax is really quite simple:

talk.sh

#!/bin/sh

echo "Please talk to me ..."

while :

do

read INPUT_STRING

case $INPUT_STRING in

hello)

echo "Hello yourself!"

;;

bye)

echo "See you again!"

break

;;

*)

echo "Sorry, I don't understand"

;;

esac

done

echo

echo "That's all folks!"

Page 30: Os lab manual

Prepared By |Mr. Neelamani Samal 30

Okay, so it's not the best conversationalist in the world; it's only an example!

Try running it and check how it works...

$ ./talk.sh

Please talk to me ...

hello

Hello yourself!

What do you think of politics?

Sorry, I don't understand

bye

See you again!

That's all folks!

$

The syntax is quite simple: The case line itself is always of the same format, and it means that we are testing the value of

the variable INPUT_STRING.

The options we understand are then listed and followed by a right bracket,

as hello) and bye).

This means that if INPUT_STRING matches hello then that section of code is executed, up to

the double semicolon.

If INPUT_STRING matches bye then the goodbye message is printed and the loop exits. Note

that if we wanted to exit the script completely then we would use the command exit instead

of break.

The third option here, the *), is the default catch-all condition; it is not required, but is often

useful for debugging purposes even if we think we know what values the test variable will have.

The whole case statement is ended with esac (case backwards!) then we end the while loop with

a done.

That's about as complicated as case conditions get, but they can be a very useful and powerful

tool. They are often used to parse the parameters passed to a shell script, amongst other uses.

foo=sun

echo $fooshine # $fooshine is undefined

echo ${foo}shine # displays the word "sunshine"

That's not all, though - these fancy brackets have a another, much more powerful use. We can

deal with issues of variables being undefined or null (in the shell, there's not much difference

between undefined and null).

Page 31: Os lab manual

Prepared By |Mr. Neelamani Samal 31

Using Default Values

Consider the following code snippet which prompts the user for input, but accepts defaults:

#!/bin/sh

echo -en "What is your name [ `whoami` ] "

read myname

if [ -z "$myname" ]; then

myname=`whoami`

fi

echo "Your name is : $myname"

The "-en" to echo tells it not to add a linebreak. On some systems, you use a "\c" at the end of the

line, instead.

This script runs like this:

steve$ ./name.sh

What is your name [ steve ]

Your name is : steve

... or, with user input:

steve$ ./name.sh

What is your name [ steve ] foo

Your name is : foo

This could be done better using a shell variable feature. By using curly braces and the special ":-"

usage, you can specify a default value to use if the variable is unset:

echo -en "What is your name [ `whoami` ] "

read myname

echo "Your name is : ${myname:-`whoami`}"

This could be considered a special case - we're using the output of the whoami command, which

prints your login name (UID). The more canonical example is to use fixed text, like this:

echo "Your name is : ${myname:-John Doe}"

As with other use of the backticks, `whoami` runs in a subshell, so any cd commands, or

setting any other variables, within the backticks, will not affect the currently-running shell.

Using and Setting Default Values

There is another syntax, ":=", which sets the variable to the default if it is undefined:

echo "Your name is : ${myname:=John Doe}"

This technique means that any subsequent access to the $myname variable will always get a

value, either entered by the user, or "John Doe" otherwise.

Page 32: Os lab manual

Prepared By |Mr. Neelamani Samal 32

Functions One often-overlooked feature of Bourne shell script programming is that you can easily write

functions for use within your script. This is generally done in one of two ways; with a simple script,

the function is simply declared in the same file as it is called.

However, when writing a suite of scripts, it is often easier to write a "library" of useful functions,

and source that file at the start of the other scripts which use the functions. This will be

shown later.

The method is the same however it is done; we will primarily be using the first way here. The

second (library) method is basically the same, except that the command

. ./library.sh

goes at the start of the script.

There could be some confusion about whether to call shell functions procedures or functions; the

definition of a function is traditionally that is returns a single value, and does not output anything.

A procedure, on the other hand, does not return a value, but may produce output. A shell function

may do neither, either or both. It is generally accepted that in shell scripts they are called

functions.

A function may return a value in one of four different ways:

Change the state of a variable or variables

Use the exit command to end the shell script

Use the return command to end the function, and return the supplied value to the

calling section of the shell script

echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caught

This is rather like C, in that exit stops the program, and return returns control to the caller.

The difference is that a shell function cannot change its parameters, though it can change global

parameters.

A simple script using a function would look like this:

function.sh

#!/bin/sh

# A simple script with a function...

add_a_user()

{

USER=$1

PASSWORD=$2

shift; shift;

# Having shifted twice, the rest is now comments ...

COMMENTS=$@

Page 33: Os lab manual

Prepared By |Mr. Neelamani Samal 33

echo "Adding user $USER ..."

echo useradd -c "$COMMENTS" $USER

echo passwd $USER $PASSWORD

echo "Added user $USER ($COMMENTS) with pass $PASSWORD"

}

###

# Main body of script starts here

###

echo "Start of script..."

add_a_user bob letmein Bob Holness the presenter

add_a_user fred badpassword Fred Durst the singer

add_a_user bilko worsepassword Sgt. Bilko the role model

echo "End of script..."

Line 4 identifies itself as a function declaration by ending in (). This is followed by {, and

everything following to the matching } is taken to be the code of that function.

This code is not executed until the function is called. Functions are read in, but basically ignored

until they are actually called.

Note that for this example the useradd and passwd commands have been prefixed with echo -

this is a useful debugging technique to check that the right commands would be executed. It also

means that you can run the script without being root or adding dodgy user accounts to your

system!

We have been used to the idea that a shell script is executed sequentially. This is not so with

functions.

In this case, the function add_a_user is read in and checked for syntax, but not executed until it

is explicitly called. Execution starts with the echo statement "Start of script...". The next line, add_a_user bob

letmein Bob Holness is recognised as a function call so the add_a_user function is entered

and starts executing with certain additions to the environment:

$1=bob

$2=letmein

$3=Bob

$4=Holness

$5=the

$6=presenter

So within that function, $1 is set to bob, regardless of what $1 may be set to outside of the

function.

So if we want to refer to the "original" $1 inside the function, we have to assign a name to it -

Page 34: Os lab manual

Prepared By |Mr. Neelamani Samal 34

such as: A=$1 before we call the function. Then, within the function, we can refer to $A.

We use the shift command again to get the $3 and onwards parameters into $@. The function

then adds the user and sets their password. It echoes a comment to that effect, and returns

control to the next line of the main code.

Scope of Variables

Programmers used to other languages may be surprised at the scope rules for shell functions.

Basically, there is no scoping, other than the parameters ($1, $2, $@, etc).

Taking the following simple code segment:

#!/bin/sh

myfunc()

{

echo "I was called as : $@"

x=2

}

### Main script starts here

echo "Script was called with $@"

x=1

echo "x is $x"

myfunc 1 2 3

echo "x is $x"

The script, when called as scope.sh a b c, gives the following output:

Script was called with a b c

x is 1

I was called as : 1 2 3

x is 2

The $@ parameters are changed within the function to reflect how the function was called. The

variable x, however, is effectively a global variable - myfunc changed it, and that change is still

effective when control returns to the main script.

Page 35: Os lab manual

Prepared By |Mr. Neelamani Samal 35

A function will be called in a sub-shell if its output is piped somewhere else - that is, "myfunc 1

2 3 | tee out.log" will still say "x is 1" the second time around. This is because a new shell

process is called to pipe myfunc(). This can make debugging very frustrating; Astrid had a

script which suddenly failed when the "| tee" was added, and it is not immediately obvious why

this must be. The tee has to be started up before the function to the left of the pipe; with the

simple example of "ls | grep foo", then grep has to be started first, with its stdin then tied

to the stdout of ls once lsstarts. In the shell script, the shell has already been started before

we even knew we were going to pipe through tee, so the operating system has to start tee, then

start a new shell to call myfunc(). This is frustrating, but well worth being aware of.

Functions cannot change the values they have been called with, either - this must be done by

changing the variables themselves, not the parameters as passed to the script.

An example shows this more clearly:

#!/bin/sh

myfunc()

{

echo "\$1 is $1"

echo "\$2 is $2"

# cannot change $1 - we'd have to say:

# 1="Goodbye Cruel"

# which is not a valid syntax. However, we can

# change $a:

a="Goodbye Cruel"

}

### Main script starts here

a=Hello

b=World

myfunc $a $b

echo "a is $a"

echo "b is $b"

This rather cynical function changes $a, so the message "Hello World" becomes "Goodbye Cruel

World".

Recursion

Functions can be recursive - here's a simple example of a factorial function:

Page 36: Os lab manual

Prepared By |Mr. Neelamani Samal 36

factorial.sh

#!/bin/sh

factorial()

{

if [ "$1" -gt "1" ]; then

i=`expr $1 - 1`

j=`factorial $i`

k=`expr $1 \* $j`

echo $k

else

echo 1

fi

}

while :

do

echo "Enter a number:"

read x

factorial $x

done

common.lib

# common.lib

# Note no #!/bin/sh as this should not spawn

# an extra shell. It's not the end of the world

# to have one, but clearer not to.

#

STD_MSG="About to rename some files..."

rename()

{

# expects to be called as: rename .txt .bak

FROM=$1

TO=$2

for i in *$FROM

do

j=`basename $i $FROM`

mv $i ${j}$TO

Page 37: Os lab manual

Prepared By |Mr. Neelamani Samal 37

done

}

function2.sh

#!/bin/sh

# function2.sh

. ./common.lib

echo $STD_MSG

rename txt bak

function3.sh

#!/bin/sh

# function3.sh

. ./common.lib

echo $STD_MSG

rename html html-bak

Here we see two user shell scripts, function2.sh and function3.sh, each sourceing the

common library file common.lib, and using variables and functions declared in that file.

This is nothing too earth-shattering, just an example of how code reuse can be done in shell

programming.

Displaying and Printing Files:

These commands allow you to see the contents of a file.

Cat to display a text file or to concatenate files

cat file1 displays contents of file1 on the screen (or

window) without any screen breaks.

cat file1 file2 displays contents of file1 followed by file2 on

the screen (or window) without any screen

breaks.

cat file1 file2 > file3 creates file3 containing file1 followed

by file2.

Diff to show the differences between two files

diff ABC DEF displays any lines in ABC or DEF that differ from

each other.

enscript to print a file with filename, date, and page number

enscript -Pxxx -2rG ABC prints out the contents of file ABC on the printer

Page 38: Os lab manual

Prepared By |Mr. Neelamani Samal 38

named xxx with two columns per page (-2),

rotated 90 degrees (-r) so that it appears in

a landscape format, with a gaudy heading (-G) as

a shaded bar across the top that provides the

filename (ABC), the creation date of that file, and

the page number.

Lpr to print a file

lpr -Pxxx ABC DEF prints out the contents of the file ABC followed by

the contents of the file DEF on printer xxx.

more to display a file, screen by screen;

to list the contents of a file to the terminal screen (or window)

more ABC DEF displays the two files ABC and DEF sequentially

on the screen. Hitting the space bar moves down

one screen; the return key moves down one line.

pr to paginate a file before printing it (to pretty it)

pr ABC DEF

breaks the contents of the files ABC and DEF into

pages, puts a heading on the top of each file with

the name of the file, the date and time, and a page

number. The two files are numbered

independently. The result goes to the screen.

pr ABC | lpr –Pxxx

paginates the file ABC and sends the resultant file

to be printed on xxx. This is an example of a

Unix command that uses a pipe) (`|'); that is, the

standard output of the first part of the command

(before the pipe `|') is piped to (is treated as the

standard input for) the second part.

spell

to perform a spelling check on a file;

to list words found in the file

that are not in the Unix spelling dictionary;

Note: often lists words that are hyphenated (split across two lines)

Conclusion :-

Page 39: Os lab manual

Prepared By |Mr. Neelamani Samal 39

Laboratory Experiment No 3 :-

Objective :- Learn the vi Editor and Programs on process creation.

Theory:-

The UNIX full screen editor `vi' is a tightly designed editing system in which

almost every letter has a function and the function is stronger for upper than

lower case. However, a letter and its actual function are usually closely related.

It is important to remember that the `(Esc)' escape key ends most functions and

a `(Esc), (Esc)' double application certainly ends the function with the ring of a

bell. The subcommand `u' undoes the last function (presumably an error). Use

`:q! (CR)' to end with out saving, especially in hopeless situations. Use `:wq

(CR)' to resave and end {`ZZ' also resaves and ends, but will not resave if the

file has been saved in another file and no further changes have been made}, or

`:w (CR)' to only resave. The character `:' prompts the UNIX line editor `ex'

which you can think of as being embedded in `vi'. Some of the above critical

`vi' subcommands are repeated below with others. Most `vi' subcommands are

not displayed when used and do not take a carriage return `(CR)'. The fact that

most keys have a meaning both as single characters and as concatenations of

several characters has many benefits, but has disadvantages in that mistakes can

turn out to be catastrophic. {Remember that `(Esc), (Esc), u' key sequence!}

{WARNING: `VI' is disabled during an IBM Telnet session.}

(Esc) : End a command; especially used with insert `i', append `a' or

replace 'R'.

(Esc), (Esc) : Ensured end of a command with bell; press the Escape-key

twice; use it.

u : Undoes last command; usually used after `(Esc)' or `(Esc), (Esc)'; if

undoing is worse then repeat `u' again to undo the undoing.

:set all (CR) : Display all vi options. Use this ex command when your

initial vi session is poor. Customized options are placed in the `.exrc' ex

resource configuration profile.

:w (CR) : Save or resave the default file being edited, but do not end.

Page 40: Os lab manual

Prepared By |Mr. Neelamani Samal 40

:w [file] (CR) : Save into a new file [file], but do not end.

:w! [file] (CR) : Save or resave into an existing file [file], but do not end.

:q (CR) : Quit vi without saving, provided no changes have been made

since the last save.

:q! (CR) : Quit vi without saving, living the file as it was in the last save.

:wq (CR) : Save the default file being edited, and quit.

ZZ : Save the edited file, provided not changes have been made since the

last save of the edited file to any file, and quit `vi'. {Warning: if you just

saved the edited file into any other file, the file will NOT be resaved.

`:wq (CR) is much safer to use.}

h or j or k or l : The arrow keys, such that

k = up

^

|

h = left <-- --> right = l

|

v

j = down

each take a number prefix that moves the cursor that many times.

(CR) : moves cursor a line forward; `+' also does.

-- : Moves cursor a line backward.

[N] (CR) : Moves cursor [N] lines forwards.

[N]-- : Moves cursor [N] lines backwards.

Ctrl-f : Moves cursor a page forward.

Ctrl-b : Moves cursor a page backward.

Ctrl-d : Moves cursor a half page down.

Ctrl-u : Moves cursor a half page up.

[L]G : Go to line [L]. `1G' moves the cursor to the beginning of the file

(BOF).

Page 41: Os lab manual

Prepared By |Mr. Neelamani Samal 41

G : Go to the last line just before the end of file (EOF) mark. `$G' does

the same thing.

0 : Go to beginning of the line (BOL).

^ : Go to beginning of the nonblank part of the line (BOL).

~ : Got to first nonblank character on a line.

$ : Go to end of the line (EOL).

[N]| : Go to column [N] of the current line.

% : Find the matching parenthesis.

/[string] (CR) : Find the next occurrence of `[string]' forwards. Use `n' to

repeat, or `N' to search backwards.

?[string] (CR) : Find the next occurrence of` [string]' backwards.

n : Repeat last `/[string] (CR)' or `?[string] (CR)'; think of the file as

being wrapped around from end to beginning, so that when you return to

the start you know that you have found all occurrences.

N : Repeat last `/[string] (CR)' or `?[string] (CR)', but in reverse.

. : Repeat last change. This is best used along with the repeat search `n'

or `N'.

i[string](Esc) : Insert a string `[string]' before current character at the

cursor; the subcommand `i' itself and other subcommands are not

displayed; a `(CR)' in the string during the insert is used to continue

input on additional lines; end with the escape key `(Esc)' or `(Esc),

(Esc)'.

o[string](Esc) : Opens a new line below the current line for insertion of

string `[string]'; end with `(Esc)' or `(Esc), (Esc)'; use for POWER

TYPING input for an old or new file; `O[string](Esc)' opens a new line

above the current line for insertion.

I[string](Esc) : Insert a string at the beginning of the current line (BOL),

else is like insert `i';a `(CR)' in the string during the insert is used to

continue input on additional lines; end with `(Esc)' or `(Esc), (Esc)'.

Page 42: Os lab manual

Prepared By |Mr. Neelamani Samal 42

J : Joins next line to current line.

a[string](Esc) : Appends a string `[string]' following the current

character at the cursor, else it works like insert `i'; use `(CR)' in the string

to continue input onto new lines; end with `(Esc)'; also use for POWER

TYPING.

A[string](Esc) : Appends a string `[string]' at the end of a line (EOL),

works like `i' or `a'; use `(CR)' in the string to continue input onto new

lines; end with `(Esc)'; also use for POWER TYPING.

r[C](SPACE) : Replace a single character over the cursor by the single

character [C]; finalize with the Space-bar.

R[string](Esc) : Replace a string of characters by `[string]' in until `(Esc)'

is typed to end.

s[string](Esc) : Substitutes the string `[string]' for the single character at

the cursor. The multiple form `[N]s[string](Esc)' substitutes `[string]' for

the `[N]' characters starting at the cursor.

x : Delete the current character at the cursor.

d(SPACE) : Deletes a single character. `[N]d(SPACE)' deletes `[N]'

characters.

dd : Deletes the current line. `[N]dd' deletes `[N]' lines.

D : Deletes from the cursor to the end of line (EOL).

dw : Deletes the current word; `[N]dw' deletes `[N]' words.

w : Move cursor to the beginning of the next word. `[N]w' moves the

cursor `[N]' words forward. `[N]b' moves it `[N]' words backward. `[N]e'

moves it to the end of the word.

[N]y(SPACE) : Yanks `[N]' characters starting at the cursor and puts

them into the default buffer. `[N]yy' yanks `[N]' lines.

p : Puts the current contents of the default buffer after the cursor if

characters or after the current line if lines. Helpful to use right after a

character yank `y' or a character delete `d' or a line yank `yy' or a line

delete `dd', along with a search `/[string](CR)' or repeat search `n'. and a

Page 43: Os lab manual

Prepared By |Mr. Neelamani Samal 43

repeat change `.'. `P' puts the contents of the default buffer before the

current line.

"b[N]Y : Yank [N] lines starting with the current line to the buffer

labeled b; the double quote {"} is used to avoid an id conflict with

subcommand names; any letter other than `x' can be used to name the

buffer; safer than the line yank `yy' because it is very easy to

accidentally change the default buffer.

"b[N]dd : Deletes [N] lines starting with the current line to the buffer

labeled `b'.

"bp : Put back lines from the buffer labeled `b' after or below the cursor;

use after a yank or delete to a labeled buffer to move groups of lines

from one location to another.

Directory Manipulation

Pwd show the directory that you are in (present working directory)

cd dir.1 change directory to dir.1

mkdir dir.1 make new directory dir.1

rmdir dir.1 remove EMPTY directory dir.1

rm -r dir.1 remove directory dir.2 AND its contents

cp -r dir.1 dir.2 copy dir.1 (and its contents) to dir.2

mv file.1 dir.1 move file.1 to dir.1

Ls

show contents of current directory. Variations:

ls dir.1 shows contents of dir.1

ls -d dir.1 shows PRESENCE of dir.1

du -sk dir.1 show sum of size (in kilobytes) of dir.1 and its contents

tar -cvf dir.1.tar dir.1 store an image of dir.1 and it's contents in file file.1

Process Control

command1& execute command1 in background

ps -ef print expanded list of all processes

kill pid1 remove process pid1

<control-c> interrupt current process

<control-z> suspend current process

jobs display background and suspended processes

Page 44: Os lab manual

Prepared By |Mr. Neelamani Samal 44

/* Program to illustrate Inter Process Communication */

#include <stdio.h>

#include <types.h>

#include <unistd.h>

#include <stdlib.h>

int main()

{

int pfd[2], i;

pid_t mypid;

if(pipe(pfd) < 0)

perror(“Pipe Error”);

if(!fork())

{

char data;

printf(“Enter a Number…\n”);

scanf(“%d”, &data);

write(pfd[1], &data, 1);

mypid = getpid();

printf(“I am process %d\n”, mypid);

printf(“My parent is process %d\n”, getppid());

printf(“Child Exiting…\n”);

exit(0);

}

else

{

char data1;

read(pfd[0], &data1, 1);

printf(“Received %d from child \n”, data1);

printf(“The odd numbers are… \n”);

for(i=1; i<=data1; i+=2)

{

printf(“%5d”, i);

sleep(2);

}

printf(“\n Parent Exiting…\n”);

exit(0);

}

return(0);

}

Conclusion :-

Page 45: Os lab manual

Prepared By |Mr. Neelamani Samal 45

Laboratory Experiment 4 :- Objective :

Learn how to link C Language in UNIX and Programs on UNIX System

calls

cc -o run [file].c : Compiles source [file].c, using the standard C

compiler and producing an executable named run.

cc -c [file].c : Compiles source [file].c, using the standard C compiler

`scc2.0' and producing an object file named [file].o.

UNIX System Calls:-

A system call is just what its name implies -- a request for the operating system to do something on behalf of the user's program. The system calls are functions used in the kernel itself. To the programmer, the system call appears as a normal C function call. However since a system call executes code in the kernel, there must be a mechanism to change the mode of a process from user mode to kernel mode. The C compiler uses a predefined library of functions (the C library)that have the names of the system calls. The library functions typically invoke an instruction that changes the process execution mode to kernel mode and causes the kernel to start executing code for system calls. The instruction that causes the mode change is often referred to as an "operating system trap" which is a software generated interrupt .The library routines execute in user mode, but the system call interface is a special case of an interrupt handler. The library functions pass the kernel a unique number per system call in a machine dependent way --either as a parameter to the operating system trap, in a particular register, or on the stack -- and the kernel thus determines the specific system call the user is invoking. In handling the operating system trap, the kernel looks up the system call number in a table to find the address of the appropriate kernel routine that is the entry point for the system call and to find the number of parameters the system call expects. The kernel calculates the (user) address of the first parameter to the system call by adding (or subtracting, depending on the direction of stack growth) an offset to the user stack pointer, corresponding to the number of the parameters to the system call. Finally, it copies the user parameters to the "u area" and call the appropriate system call routine. After executing the code for the system call, the kernel determines whether there was an error. If so ,it adjusts register locations in the saved user register context ,typically setting the "carry" bit for the PS (processor status) register and copying the error number into register 0 location. If there were no errors in the execution of the system call, the kernel clears the "carry" bit in the PS register and copies the appropriate return values from the system call into the locations for registers 0 and 1 in the saved user register context. When the kernel returns from the operating system trap to user mode, it returns to the library instruction afterthe trap instruction. The library interprets the return values from the kernel and returns a value to the user program. UNIX system calls are used to manage the file system, control processes, and to provide inter process communication. The UNIX system interface

Page 46: Os lab manual

Prepared By |Mr. Neelamani Samal 46

consists of about 80 system calls (as UNIX evolves this number willincrease).The

following table lists about 40 of the more important system call:

GENERAL CLASS SPECIFIC CLASS SYSTEM CALL

File Structure Creating a Channel creat()

Related Calls open()

close()

Input/Output read()

write()

Random Access lseek()

Channel Duplication dup()

Aliasing and Removing link()

Files unlink()

File Status stat()

fstat()

Access Control access()

chmod()

chown()

umask()

Device Control ioctl()

---------------------------------------------------------------------

Process Related Process Creation and exec()

Calls Termination fork()

wait()

exit()

Process Owner and Group getuid()

geteuid()

getgid()

getegid()

Process Identity getpid()

getppid()

Process Control signal()

kill()

alarm()

Change Working Directory chdir()

----------------------------------------------------------------------

Interprocess Pipelines pipe()

Communication Messages msgget()

msgsnd()

msgrcv()

msgctl()

Semaphores semget()

semop()

Shared Memory shmget()

shmat()

shmdt()

Page 47: Os lab manual

Prepared By |Mr. Neelamani Samal 47

/* errmsg1.c

print all system error messages using "perror()"

*/

#include <stdio.h>

int main()

{

int i;

extern int errno, sys_nerr;

for (i = 0; i < sys_nerr; ++i)

{

fprintf(stderr, "%3d",i);

errno = i;

perror(" ");

}

exit (0);

}

/* errmsg2.c

print all system error messages using the global error message

table.

*/

#include <stdio.h>

int main()

{

int i;

extern int sys_nerr;

extern char *sys_errlist[];

fprintf(stderr,"Here are the current %d error

messages:\n\n",sys_nerr);

for (i = 0; i < sys_nerr; ++i)

fprintf(stderr,"%3d: %s\n", i, sys_errlist[i]);

}

Conclusion :-