ptg10805159
Section 3.14 fcntlFunction 85
operation of the program, when invoked frombash(the Bourne-again shell). Results
will vary,depending on which shell you use.
$./a.out 0 < /dev/tty
read only
$./a.out 1 > temp.foo
$cat temp.foo
write only
$./a.out 2 2>>temp.foo
write only, append
$./a.out 5 5<>temp.foo
read write
The clause5<>temp.fooopens the filetemp.foofor reading and writing on file
descriptor 5.
Example
When we modify either the file descriptor flags or the file status flags, we must be
careful to fetch the existing flag value, modify it as desired, and then set the new flag
value. Wecan’t simply issue anF_SETFDor anF_SETFLcommand, as this could turn
offflag bits that werepreviously set.
Figure3.12 shows a function that sets one or more of the file status flags for a
descriptor.
#include "apue.h"
#include <fcntl.h>
void
set_fl(int fd, int flags) /* flags are file status flags to turn on */
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0)
err_sys("fcntl F_GETFL error");
val |= flags; /* turn on flags */
if (fcntl(fd, F_SETFL, val) < 0)
err_sys("fcntl F_SETFL error");
}
Figure 3.12 Turn on one or more of the file status flags for a descriptor
If we change the middle statement to
val &= ̃flags; /* turn flags off */
we have a function namedclr_fl,which we’ll use in some later examples. This
statement logically ANDs the one’s complement offlagswith the currentval.