]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - share/doc/psd/04.uprog/p4
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / share / doc / psd / 04.uprog / p4
1 .\" Copyright (C) Caldera International Inc. 2001-2002.  All rights reserved.
2 .\" 
3 .\" Redistribution and use in source and binary forms, with or without
4 .\" modification, are permitted provided that the following conditions are
5 .\" met:
6 .\" 
7 .\" Redistributions of source code and documentation must retain the above
8 .\" copyright notice, this list of conditions and the following
9 .\" disclaimer.
10 .\" 
11 .\" Redistributions in binary form must reproduce the above copyright
12 .\" notice, this list of conditions and the following disclaimer in the
13 .\" documentation and/or other materials provided with the distribution.
14 .\" 
15 .\" All advertising materials mentioning features or use of this software
16 .\" must display the following acknowledgement:
17 .\" 
18 .\" This product includes software developed or owned by Caldera
19 .\" International, Inc.  Neither the name of Caldera International, Inc.
20 .\" nor the names of other contributors may be used to endorse or promote
21 .\" products derived from this software without specific prior written
22 .\" permission.
23 .\" 
24 .\" USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
25 .\" INTERNATIONAL, INC.  AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
26 .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27 .\" WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28 .\" DISCLAIMED.  IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE
29 .\" FOR ANY DIRECT, INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
32 .\" BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 .\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
34 .\" OR OTHERWISE) RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
35 .\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 .\" 
37 .\" $FreeBSD$
38 .\"
39 .\"     @(#)p4  8.1 (Berkeley) 6/8/93
40 .\"
41 .NH
42 LOW-LEVEL I/O
43 .PP
44 This section describes the 
45 bottom level of I/O on the
46 .UC UNIX
47 system.
48 The lowest level of I/O in
49 .UC UNIX
50 provides no buffering or any other services;
51 it is in fact a direct entry into the operating system.
52 You are entirely on your own,
53 but on the other hand,
54 you have the most control over what happens.
55 And since the calls and usage are quite simple,
56 this isn't as bad as it sounds.
57 .NH 2
58 File Descriptors
59 .PP
60 In the
61 .UC UNIX
62 operating system,
63 all input and output is done
64 by reading or writing files,
65 because all peripheral devices, even the user's terminal,
66 are files in the file system.
67 This means that a single, homogeneous interface
68 handles all communication between a program and peripheral devices.
69 .PP
70 In the most general case,
71 before reading or writing a file,
72 it is necessary to inform the system
73 of your intent to do so,
74 a process called
75 ``opening'' the file.
76 If you are going to write on a file,
77 it may also be necessary to create it.
78 The system checks your right to do so
79 (Does the file exist?
80 Do you have permission to access it?),
81 and if all is well,
82 returns a small positive integer
83 called a
84 .ul
85 file descriptor.
86 Whenever I/O is to be done on the file,
87 the file descriptor is used instead of the name to identify the file.
88 (This is roughly analogous to the use of
89 .UC READ(5,...)
90 and
91 .UC WRITE(6,...)
92 in Fortran.)
93 All
94 information about an open file is maintained by the system;
95 the user program refers to the file
96 only
97 by the file descriptor.
98 .PP
99 The file pointers discussed in section 3
100 are similar in spirit to file descriptors,
101 but file descriptors are more fundamental.
102 A file pointer is a pointer to a structure that contains,
103 among other things, the file descriptor for the file in question.
104 .PP
105 Since input and output involving the user's terminal
106 are so common,
107 special arrangements exist to make this convenient.
108 When the command interpreter (the
109 ``shell'')
110 runs a program,
111 it opens
112 three files, with file descriptors 0, 1, and 2,
113 called the standard input,
114 the standard output, and the standard error output.
115 All of these are normally connected to the terminal,
116 so if a program reads file descriptor 0
117 and writes file descriptors 1 and 2,
118 it can do terminal I/O
119 without worrying about opening the files.
120 .PP
121 If I/O is redirected 
122 to and from files with
123 .UL < 
124 and
125 .UL > ,
126 as in
127 .P1
128 prog <infile >outfile
129 .P2
130 the shell changes the default assignments for file descriptors
131 0 and 1
132 from the terminal to the named files.
133 Similar observations hold if the input or output is associated with a pipe.
134 Normally file descriptor 2 remains attached to the terminal,
135 so error messages can go there.
136 In all cases,
137 the file assignments are changed by the shell,
138 not by the program.
139 The program does not need to know where its input
140 comes from nor where its output goes,
141 so long as it uses file 0 for input and 1 and 2 for output.
142 .NH 2
143 Read and Write
144 .PP
145 All input and output is done by
146 two functions called
147 .UL read
148 and
149 .UL write .
150 For both, the first argument is a file descriptor.
151 The second argument is a buffer in your program where the data is to
152 come from or go to.
153 The third argument is the number of bytes to be transferred.
154 The calls are
155 .P1
156 n_read = read(fd, buf, n);
157
158 n_written = write(fd, buf, n);
159 .P2
160 Each call returns a byte count
161 which is the number of bytes actually transferred.
162 On reading,
163 the number of bytes returned may be less than
164 the number asked for,
165 because fewer than
166 .UL n
167 bytes remained to be read.
168 (When the file is a terminal,
169 .UL read
170 normally reads only up to the next newline,
171 which is generally less than what was requested.)
172 A return value of zero bytes implies end of file,
173 and
174 .UL -1
175 indicates an error of some sort.
176 For writing, the returned value is the number of bytes
177 actually written;
178 it is generally an error if this isn't equal
179 to the number supposed to be written.
180 .PP
181 The number of bytes to be read or written is quite arbitrary.
182 The two most common values are 
183 1,
184 which means one character at a time
185 (``unbuffered''),
186 and
187 512,
188 which corresponds to a physical blocksize on many peripheral devices.
189 This latter size will be most efficient,
190 but even character at a time I/O
191 is not inordinately expensive.
192 .PP
193 Putting these facts together,
194 we can write a simple program to copy
195 its input to its output.
196 This program will copy anything to anything,
197 since the input and output can be redirected to any file or device.
198 .P1
199 #define BUFSIZE 512     /* best size for PDP-11 UNIX */
200
201 main()  /* copy input to output */
202 {
203         char    buf[BUFSIZE];
204         int     n;
205
206         while ((n = read(0, buf, BUFSIZE)) > 0)
207                 write(1, buf, n);
208         exit(0);
209 }
210 .P2
211 If the file size is not a multiple of
212 .UL BUFSIZE ,
213 some 
214 .UL read
215 will return a smaller number of bytes
216 to be written by
217 .UL write ;
218 the next call to 
219 .UL read
220 after that
221 will return zero.
222 .PP
223 It is instructive to see how
224 .UL read
225 and
226 .UL write
227 can be used to construct
228 higher level routines like
229 .UL getchar ,
230 .UL putchar ,
231 etc.
232 For example,
233 here is a version of
234 .UL getchar
235 which does unbuffered input.
236 .P1
237 #define CMASK   0377    /* for making char's > 0 */
238
239 getchar()       /* unbuffered single character input */
240 {
241         char c;
242
243         return((read(0, &c, 1) > 0) ? c & CMASK : EOF);
244 }
245 .P2
246 .UL c
247 .ul
248 must
249 be declared
250 .UL char ,
251 because
252 .UL read
253 accepts a character pointer.
254 The character being returned must be masked with
255 .UL 0377
256 to ensure that it is positive;
257 otherwise sign extension may make it negative.
258 (The constant
259 .UL 0377
260 is appropriate for the
261 .UC PDP -11
262 but not necessarily for other machines.)
263 .PP
264 The second version of
265 .UL getchar
266 does input in big chunks,
267 and hands out the characters one at a time.
268 .P1
269 #define CMASK   0377    /* for making char's > 0 */
270 #define BUFSIZE 512
271
272 getchar()       /* buffered version */
273 {
274         static char     buf[BUFSIZE];
275         static char     *bufp = buf;
276         static int      n = 0;
277
278         if (n == 0) {   /* buffer is empty */
279                 n = read(0, buf, BUFSIZE);
280                 bufp = buf;
281         }
282         return((--n >= 0) ? *bufp++ & CMASK : EOF);
283 }
284 .P2
285 .NH 2
286 Open, Creat, Close, Unlink
287 .PP
288 Other than the default
289 standard input, output and error files,
290 you must explicitly open files in order to
291 read or write them.
292 There are two system entry points for this,
293 .UL open
294 and
295 .UL creat 
296 [sic].
297 .PP
298 .UL open
299 is rather like the
300 .UL  fopen
301 discussed in the previous section,
302 except that instead of returning a file pointer,
303 it returns a file descriptor,
304 which is just an
305 .UL int .
306 .P1
307 int fd;
308
309 fd = open(name, rwmode);
310 .P2
311 As with
312 .UL fopen ,
313 the
314 .UL name
315 argument
316 is a character string corresponding to the external file name.
317 The access mode argument
318 is different, however:
319 .UL rwmode
320 is 0 for read, 1 for write, and 2 for read and write access.
321 .UL open
322 returns
323 .UL -1
324 if any error occurs;
325 otherwise it returns a valid file descriptor.
326 .PP
327 It is an error to 
328 try to
329 .UL open
330 a file that does not exist.
331 The entry point
332 .UL creat
333 is provided to create new files,
334 or to re-write old ones.
335 .P1
336 fd = creat(name, pmode);
337 .P2
338 returns a file descriptor
339 if it was able to create the file
340 called
341 .UL name ,
342 and
343 .UL -1
344 if not.
345 If the file
346 already exists,
347 .UL creat
348 will truncate it to zero length;
349 it is not an error to
350 .UL creat
351 a file that already exists.
352 .PP
353 If the file is brand new,
354 .UL creat
355 creates it with the
356 .ul
357 protection mode 
358 specified by
359 the
360 .UL pmode
361 argument.
362 In the
363 .UC UNIX
364 file system,
365 there are nine bits of protection information
366 associated with a file,
367 controlling read, write and execute permission for
368 the owner of the file,
369 for the owner's group,
370 and for all others.
371 Thus a three-digit octal number
372 is most convenient for specifying the permissions.
373 For example,
374 0755
375 specifies read, write and execute permission for the owner,
376 and read and execute permission for the group and everyone else.
377 .PP
378 To illustrate,
379 here is a simplified version of
380 the
381 .UC UNIX
382 utility
383 .IT cp ,
384 a program which copies one file to another.
385 (The main simplification is that our version
386 copies only one file,
387 and does not permit the second argument
388 to be a directory.)
389 .P1
390 #define NULL 0
391 #define BUFSIZE 512
392 #define PMODE 0644 /* RW for owner, R for group, others */
393
394 main(argc, argv)        /* cp: copy f1 to f2 */
395 int argc;
396 char *argv[];
397 {
398         int     f1, f2, n;
399         char    buf[BUFSIZE];
400
401         if (argc != 3)
402                 error("Usage: cp from to", NULL);
403         if ((f1 = open(argv[1], 0)) == -1)
404                 error("cp: can't open %s", argv[1]);
405         if ((f2 = creat(argv[2], PMODE)) == -1)
406                 error("cp: can't create %s", argv[2]);
407
408         while ((n = read(f1, buf, BUFSIZE)) > 0)
409                 if (write(f2, buf, n) != n)
410                         error("cp: write error", NULL);
411         exit(0);
412 }
413 .P2
414 .P1
415 error(s1, s2)   /* print error message and die */
416 char *s1, *s2;
417 {
418         printf(s1, s2);
419         printf("\en");
420         exit(1);
421 }
422 .P2
423 .PP
424 As we said earlier,
425 there is a limit (typically 15-25)
426 on the number of files which a program
427 may have open simultaneously.
428 Accordingly, any program which intends to process
429 many files must be prepared to re-use
430 file descriptors.
431 The routine
432 .UL close
433 breaks the connection between a file descriptor
434 and an open file,
435 and frees the
436 file descriptor for use with some other file.
437 Termination of a program
438 via
439 .UL exit
440 or return from the main program closes all open files.
441 .PP
442 The function
443 .UL unlink(filename)
444 removes the file
445 .UL filename
446 from the file system.
447 .NH 2
448 Random Access \(em Seek and Lseek
449 .PP
450 File I/O is normally sequential:
451 each
452 .UL read
453 or
454 .UL write
455 takes place at a position in the file
456 right after the previous one.
457 When necessary, however,
458 a file can be read or written in any arbitrary order.
459 The
460 system call
461 .UL lseek
462 provides a way to move around in
463 a file without actually reading
464 or writing:
465 .P1
466 lseek(fd, offset, origin);
467 .P2
468 forces the current position in the file
469 whose descriptor is
470 .UL fd
471 to move to position
472 .UL offset ,
473 which is taken relative to the location
474 specified by
475 .UL origin .
476 Subsequent reading or writing will begin at that position.
477 .UL offset
478 is
479 a
480 .UL long ;
481 .UL fd
482 and
483 .UL origin
484 are
485 .UL int 's.
486 .UL origin
487 can be 0, 1, or 2 to specify that 
488 .UL offset
489 is to be
490 measured from
491 the beginning, from the current position, or from the
492 end of the file respectively.
493 For example,
494 to append to a file,
495 seek to the end before writing:
496 .P1
497 lseek(fd, 0L, 2);
498 .P2
499 To get back to the beginning (``rewind''),
500 .P1
501 lseek(fd, 0L, 0);
502 .P2
503 Notice the
504 .UL 0L
505 argument;
506 it could also be written as
507 .UL (long)\ 0 .
508 .PP
509 With 
510 .UL lseek ,
511 it is possible to treat files more or less like large arrays,
512 at the price of slower access.
513 For example, the following simple function reads any number of bytes
514 from any arbitrary place in a file.
515 .P1
516 get(fd, pos, buf, n) /* read n bytes from position pos */
517 int fd, n;
518 long pos;
519 char *buf;
520 {
521         lseek(fd, pos, 0);      /* get to pos */
522         return(read(fd, buf, n));
523 }
524 .P2
525 .PP
526 In pre-version 7
527 .UC UNIX ,
528 the basic entry point to the I/O system
529 is called
530 .UL seek .
531 .UL seek
532 is identical to
533 .UL lseek ,
534 except that its
535 .UL  offset 
536 argument is an
537 .UL int
538 rather than  a
539 .UL long .
540 Accordingly,
541 since
542 .UC PDP -11
543 integers have only 16 bits,
544 the
545 .UL offset
546 specified
547 for
548 .UL seek
549 is limited to 65,535;
550 for this reason,
551 .UL origin
552 values of 3, 4, 5 cause
553 .UL seek
554 to multiply the given offset by 512
555 (the number of bytes in one physical block)
556 and then interpret
557 .UL origin
558 as if it were 0, 1, or 2 respectively.
559 Thus to get to an arbitrary place in a large file
560 requires two seeks, first one which selects
561 the block, then one which
562 has
563 .UL origin
564 equal to 1 and moves to the desired byte within the block.
565 .NH 2
566 Error Processing
567 .PP
568 The routines discussed in this section,
569 and in fact all the routines which are direct entries into the system
570 can incur errors.
571 Usually they indicate an error by returning a value of \-1.
572 Sometimes it is nice to know what sort of error occurred;
573 for this purpose all these routines, when appropriate,
574 leave an error number in the external cell
575 .UL errno .
576 The meanings of the various error numbers are
577 listed
578 in the introduction to Section II
579 of the
580 .I
581 .UC UNIX
582 Programmer's Manual,
583 .R
584 so your program can, for example, determine if
585 an attempt to open a file failed because it did not exist
586 or because the user lacked permission to read it.
587 Perhaps more commonly,
588 you may want to print out the
589 reason for failure.
590 The routine
591 .UL perror
592 will print a message associated with the value
593 of
594 .UL errno ;
595 more generally,
596 .UL sys\_errno
597 is an array of character strings which can be indexed
598 by
599 .UL errno
600 and printed by your program.