#include	<errno.h>
#include	<sys/file.h>
#include	<pthread.h>
#include	<stdlib.h>

int	fp;

void*	sub_thread (void* arg)
{
	char	buf[64];

	fp = open ("tag", O_RDWR, 0);
	if (fp < 0)
		printf ("Failed to open file\n");
	
	if (flock (fp,  LOCK_EX | LOCK_NB) != 0)
		printf ("failed to lock file\n");

	strcpy (buf, "test msfio_lock\n");
	write (fp, buf, strlen(buf)+1);

	return NULL;
}

int	main()
{
	pthread_t	pthr;

	system ("touch tag");
	pthread_create (&pthr, 0, sub_thread, 0);
	pthread_join (pthr, 0);

	if (flock (fp, LOCK_UN) != 0)
		printf ("failed to unlock file\n");

	if (flock (fp,  LOCK_EX) != 0)
	{
		printf ("failed to lock file in main thread errno=%d\n", errno);
		perror ();
	}
	if (close (fp) != 0)
		printf ("failed to close file\n");
	return 0;
}
