/* testlock.c - Test file locking
 *
 * Copyright (C) 2001 Alan Shutko
 *
 * 
 * Description:
 * 
 *  This program tests whether file locking works for a given
 *  pathname.  This is useful for checking whether file locking will
 *  work over your NFS, SMB or other networked filesystem.
 *
 *  The program will try to acquire a lock on a file, and will hold
 *  that lock until you hit return.  This tests whether the fs reports
 *  to allow locks.  You can check if the file is actually locked by
 *  running a second instance of this program on the same file while
 *  the first is running: it should fail to obtain the lock.
 * 
 * History:
 * ats     2/26/01    Created
 *
 * Tokens: ::Header:: testlock.h
 */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

int main(int argc, char **argv)
{
    int fd;
    struct flock lk;
    char input[2];
    
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s lockfile", argv[0]);
        exit(1);
    }

    if ((fd = open(argv[1], O_RDWR)) < 0)
    {
        perror("Could not open file");
        exit(1);
    }

    lk.l_type = F_WRLCK;
    lk.l_whence = SEEK_SET;
    lk.l_start = 0;
    lk.l_len = 0;
    
    errno = 0;
    if (fcntl(fd, F_SETLK, &lk) < 0)
    {
        perror("Could not lock file");
        exit(1);
    }
    fprintf(stderr, "Lock successful.  Hit return to continue.\n");
    fgets(input, sizeof(input), stdin);
    exit(0);
}


