Next | Prev | Up | Top | Contents | Index

Opening a File for Record Locking

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 used, then the file must be opened with at least read access; likewise for write locks and write access.

Example 4-1 opens a file for both read and write access.

Example 4-1 : Opening a File for Locked Use

#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 database 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 to perform both locking and I/O functions. The next step is to set a lock.


Next | Prev | Up | Top | Contents | Index