Bug report from : Michael Kerrisk , self
(Note that the reply-to line automatically redirects
to yyyyyyyyyyyyyy@xxxxxxxxxxxxx for further discussion on bug reports)
@ page 1 line 10935 section fcntl() comment {examples for fcntl()}
Problem:
These are two EXAMPLES for the fcntl() man page. Line number
references are to TC1. If the example needs to be shortened,
then the code to remove the file lock could be cut, and the
explanatory text suitably amended.
Action:
Change
"None"
to the following:
[Summary] Locking and unlocking a file
The following example demonstrates how to place a lock on
bytes 100 to 109 of a file and then later remove it.
F_SETLK is used to perform a non-blocking lock request so
that the process does not have to wait if an incompatible
is held by another process; instead the process can take
some other action.
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int
main(int argc, char *argv[])
{
int fd;
struct flock fl;
fd = open("testfile", O_RDWR);
if (fd == -1)
/* Handle error */;
/* Make a non-blocking request to place a write lock
on bytes 100-109 of testfile */
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == -1) {
if (errno == EACCES || errno == EAGAIN) {
printf("Already locked by another process\n");
/* We can't get the lock at the moment */
} else {
/* Handle unexpected error */;
}
} else { /* Lock was granted... */
/* Perform I/O on bytes 100 to 109 of file */
/* Unlock the locked bytes */
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == -1)
/* Handle error */;
}
exit(EXIT_SUCCESS);
} /* main */
[Summary] Setting the close-on-exec flag
The following example demonstrates how to set the close on
exec flag for the file descriptor fd.
#include <unistd.h>
#include <fcntl.h>
...
int flags;
flags = fcntl(fd, F_GETFD);
if (flags == -1)
/* Handle error */;
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1)
/* Handle error */;
|