0 ratings0% found this document useful (0 votes) 39 views8 pagesSystem Programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
systems pros
a some questions should be p
ind shell? Since UNIX is
NIX system hi
? The answers
handled
ywavhat the U
Now thatyou kno :
processes
diready How are filesand
thatare inter
iI library thatis availat
sallow ins ‘yelookat files and
mming nature o
programmes you are
and applications that ensure ©
flict. This chapter t@
he same for processes:
rove the existing ones.
in the system ¢
chapterandthefollowit
wuse of the multiprogr
quired
hat resources are s
kes up file internals and the
The knowledge you acquire from th
Becai
proc t
todevise programs
to, and without causing CO!
calls; the next chapter does
you write new tools and imp!
wuar You WILL LEARN
«The basics of system calls and library fun
« Perform file I/O with open, read, write, Jseek and close, using a file descrip
« How system call errors are handled and reported with perror and stret
« Navigate a directory structure with chdir and getewd.
« Read directory entries with opendir and readdir, and cxamine the di)
. The combined role of the stat structure and stat calls in retrieving inc
+ Use S_IP4T and the $_ISexx macros to determine the fil a
+ How to use symbolic constants to test each issit ‘ oe
permission bit ofa file.
1ctiONs.
_ ToPICS OF SPECIAL INTEREST
« Understa, ;
e Kodera bgp io ors and theconstauace cea
portant to properly set the size of the b of using it with anfase UNIX: Concepts and Applications
| purposes system calls b
i) of all types (int, ch
pe declaration of this wr
23.1.2 Anatomy of a System Call z
vy are implemented, fof 2 P
renerally, ot EXce
nis (eneal oee ae toty
Irrespective of the way the
functions. They accept argu me
pointers, etc.) and return values as ea"
*/ ze_t count)s
seize t write(int ja const void “buf, $17°—
type is of
return
is oftype size, ay wpe lsat
sv spectively on your machine, ony a
pectively. int itself could be 16 bits on
size_t and ssize_t, rather than
ping, will be performed by th ;
many system «
C introduced the concept of a generic data type tthe VO A 7
write) use this data type. In the prototype for write shown ve void ae
buffer which can be for char * buf int *buf, etc, We don't nee! He
type that we actually use in our program.
The third argument
ultimately translate them to the pri ;
be typedet'd to unsigned int and int, respe
could represent unsigned long and ong, F
ed type
and 32 bits on another, By using the derived types, $17°—
J that appropriate ma
types in our programs, we are assured
alike library function’ that often return null on érfor, system Calls generally rete
system call also séts a static (global) variable, errno, to. 2 numeric value repress
There’s a text message associated with every error number, and we'll learn to id
the crror and print these messages. Some system calls, however, never return
never return atall.
23.1.3 Atomic Operations
When you program in this multiprogramming environment, there’s one thing
keep in mind at all times: Multiple processes can contend for a single resoure
can be serious consequences in using two system calls (open and 1seek) to app
‘one would have sufficed (open). It’s possible that a process is taken out of the CPU ;
before Iseek, and a second process could overwrite the file in this period.
Wherever possible, you need to take care that certain critical operations are pet
manner. An atomic operation comprises multiple actions that are either perform
‘or not at all. Using two system calls in succession can’t be an atomic operation |
2 second process to run in between. In this chapter and the next, we'll note the i
behavior as and when we encounter them.
Tip: The UNIX man documentation features system calls and li
" n id lib
respectively. Sometimes, the same name represents fot ak ee
read, write and exec), so calling man without the section number would wrong
jor the command. (man read shows the man 's buil
useman 2 read (or man -s2 ren on Saas). Te ocumraton eeeOPENING AND cy,
23.2 Os)
_ begin our discussion g NG 4 Fy 5
fe Ns ILE stems
write, Cl0Se and Tega tem
fev ering 1s¢ek) ake ee lswith ming |Fites 495)
ell ¢ Te Used with phere UNE oT Teateg “I
open: Openi ESE Ob ag TERE cya Ale 70) »
3.2.1 oP Pening ang ens Heets agg, cven Pines ay These comp
ou don't asa to opena file one ating aFile MI sockets ag ay Mend
jen it. open has two forms. 8S its atek; of these
afi doesn't. Both forms oa a form ste,
ut
| su YOU can’
Pressed hy, Bh thatthe fie ne OF Write a file unt
‘Ntax: Sts, a Unless you first
t open(const char *, :
Path, ing Offa Ind the second g
gpen urns file descriptors, ee Rasiiioe 4
nimentne an int. Th :
as eee by the other four aie S the lowest
{having the descriptors 0, 1 anda - Since every Umber available
close them). Normal Pen, We done «2 Program al efor allocation and
w Normally the fest pan ON ted tgpen 3 find the thee saan
me first argument (puch) isa poin OUr rogram should files from our programs (th 2
ite fi ees
absolute or relative). The second argues tt sting that turn the file descriptor 3 ig
ea-write), which is conveniently a ee is) isusedto aaa patie pathname (cither
only one of the following mod sented by three a ode of opening (read, write o
'B modes mustbe specified: Mele const afl
fants, When opening a fi
> ROONLY Opens slg —— opening a file,
O.WRONLY Opens file for writing.
ROWR Opens file for reading and writing
These constants are defined im the file Font! -h
#include at the top of your progra
one or more of the following status flags (also
in /usr/include, so you need to place the statement
im. For added functionality, you'll often need to use
defined in fent1.h) as components of oflag:
0_APPEND Opens file in append mode (only if file opening mode is 0_WRONLY or O_RDWR).
0_TRUNC Truncates file to zero length (same conditions as above).
0 CREAT Creates file iffit doesn't exist.
0_EXCL Generates an error if 0_CREAT is also specified and the file also exists.
0. SYNC Synchronizes read-write operations. Ensures thatwrite doesn’t return until the
data is written to disk (explained later).
ed with the bit-wise OR operator, |, along with the mode of opening, Here
These status flags are us P
t EXISTS:
ays you can use open with a file tha
wee The file descriptor
int fd; F ae
fd = open("/ete/passwd”s 0_ROONLY) 5 " Seni
fd = open("foo.txt™ O.WRONLY | 0. APPEND). 5 Fe gathe >to
a ven (toate aa Se the file This pointer determine:
i inter to the beginning ofthe Wie S a
: sets the leo Por the second cal, the file is op
The first open call above fil ad or write will take ple: ee ie a SOF Asubsequen
where in the file the subsequent hich sets
for writing but only by appending psa) i
———-—~—F Shr[B56 unex: concepts and Applications
js file but im
sgsize. The third call truncatesa file
creases i
he beginning:
0 CREAT (and sometimess 0_EXCL also), to ex
reed for this function.) In that case, you'll hay
nent. This argument can be specifi
Jar you'll have co prefix the number
| to use the symbolic constants proy
write call here doesn’t overwrite th
(© TRUNC) and positions the offset P
n use the
inter att
Ifthe file doesn’t exist, t
file. (Previously, the creat system
the absolute permissions of the
octal number in the same way use¢
(like 0644 instead of 644). How you
tys/stat.h, They are displayed in a tabular form
as
the third argu
{ by chmod, except
1 are advised
below:
lw
as
User Group miner a
~ SaRUSR S_IRGRP s_1ROTH S_IRWKU
_TWUSR S_IWGRP s_IWOTH S_IRWXG
cute S_IXUSR S_IXGRP xoTH s_IRWKO
o OR these constants
ented by a separate bit, you have t
, 0644 is the same as
Since each permission is repre:
obtain the desired permissions, For instanc
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
‘on (0_TRUNC), while ensuring that the file is
To open a file for writing after truncati Y
doesn’t exist (0_CREAT), specify the permissions as the third argument:
fd = open("foo.txt", O_WRONLY | 0 CREAT | O_TRUNC, Second argument
S_IRUSR | S_IWUSR | S_IRGRP | S_TROTH) 5 Permissions are 06
This is how the shell opens a file or overwrites one that exists when it sees the > symb
the bit-wise OR of the opening mode and status flags equates to octal 01101. We ca
these numbers; that’s why we must use symbolic constants. vo
The status flag, 0_EXCL, provides protection from overwriting an existing file. If used at
be combined with 0_CREAT (0_CREAT | 0 EXCL). With the two flags set in this way, 0
an error (-1) ifthe file exists. We can use this mechanism to test for the existence ofa
Note: The file may not be created with the exact permissions open.
26 you specify with
flag. The specified permissions get reduced by the umask value of the process.
system call named umask for handling this function and is discussed in Section 23.5.
Tip: The 0_EXCL feature comes in handy when i
) ‘ you devise a scheme to let
foo, in a cooperative manner. To make the scheme work as an acbisoiy fea 0
Bore ene oes ee ie) create 3 lock file (with the same name) before they
en they are done with foo. If all cooperating ,
their open calls that attempt to create the lock file, the pe a wa se
Adherence to this agreement ensures that a file is not written simultaneously by.
\7.2 close: Closing ak
gram automatically clos
icitly when you no |
(int fd);
d practice to close
- ccurns 0 if successfia)
clos
; afi:
cand ma es it available i
‘ descriptor for that
Het reek calls invoked to
Mis in Section
ve same file is opened by ty
nel simply assigns two
aciply release the dese}
\e having descriptor values 1
-d in the next chapter,
like fwrite, fputs,
read and write. These call
and writing. We'll soon le:
Hf you sie to Pioeae
address to read:
int fd, ng aa b
while ((n =