#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

int main()
{
	int handle;
	int result;
	struct flock lock;
	int lasterr;

	printf ("Trying opening...\n");
	handle = open ("testlock_testfile", O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
	if (handle == -1) {
		lasterr = errno;
		perror (NULL);
		printf ("errno = %d\n", lasterr);
		exit (-1);
	}
	printf ("File opened!\n");

	printf ("Trying locking...\n");
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	result = fcntl (handle, F_SETLK, &lock);
	if (result == -1) {
		lasterr = errno;
		perror (NULL);
		printf ("errno = %d\n", lasterr);
		exit (-1);
	}
	printf ("File locked!\n");

	printf ("Hit Return to continue...\n");
	getchar();

	printf ("Trying unlocking...\n");
	lock.l_type = F_UNLCK;
	result = fcntl (handle, F_SETLK, &lock);
	if (result == -1) {
		lasterr = errno;
		perror (NULL);
		printf ("errno = %d\n", lasterr);
		exit (-1);
	}
	printf ("File unlocked!\n");

	return 0;
}

