|
|
The first requirement for locking a file or segment of a file is having a valid open file descriptor. If read locks are to be done, then the file must be opened with at least read accessibility, and with write accessibility for write locks.
For our example we will open our file for both read and write access:
#include <stdio.h> #include <errno.h> #include <fcntl.h>int fd; /* file descriptor */ char *filename;
main(argc, argv) int argc; char *argv[]; { extern void exit(), perror();
/* get data base file name from command line and open the * file for read and write access. */ if (argc < 2) { (void) fprintf(stderr, "usage: %s filename\n", argv[0]); exit(2); } filename = argv[1]; fd = open(filename, O_RDWR); if (fd < 0) { perror(filename); exit(2); } . . .
The file is now open for us to perform both locking and I/O functions. We then proceed with the task of setting a lock.