/*
 * File-locking calls
 *
 * AcquireLock() - acquire an exclusive lock on an open file
 * ReleaseLock() - release a lock on an open file
 *
 * The argument to both calls is a FILE *
 */

#if !HAS_FCNTL && !HAS_FLOCK
*** error -- neither fcntl() nor flock() are present?
#endif

#include	<stdio.h>
#if HAS_FCNTL
#include	<fcntl.h>
#endif
#if HAS_FLOCK
#include	<sys/file.h>
#endif

#include	"portlib.h"

/*
 * Some braindamaged systems don't define this in fcntl.h.
 */

#ifndef SEEK_SET
#define SEEK_SET 0
#endif


#if HAS_FCNTL		/* fcntl() version of locking functions */
int
AcquireLock (f)
FILE	*f;
{
struct flock	lock;
int	fd;

#ifdef DEBUG
printf ("using fcntl() on fileno %d\n", fileno (f));
#endif
	lock.l_type = F_WRLCK;
	lock.l_start = 0;
	lock.l_whence = SEEK_SET;
	lock.l_len = 0;
	fd = fileno (f);
	if (fcntl (fd, F_SETLK, &lock) == 0)
		return (1);
#ifdef DEBUG
	perror ("AcquireLock");
#endif
	return (0);
}


void
ReleaseLock (f)
FILE	*f;
{
struct flock	lock;
int	fd;

	lock.l_type = F_UNLCK;
	lock.l_start = 0;
	lock.l_whence = SEEK_SET;
	lock.l_len = 0;
	fd = fileno (f);
	(void) fcntl (fd, F_SETLK, &lock);
}

#else

#if HAS_FLOCK		/* flock() version of locking functions */

int
AcquireLock (f)
FILE	*f;
{
int	fd;

#ifdef DEBUG
printf ("using flock() on fileno %d\n", fileno (f));
#endif
	fd = fileno (f);
	if (flock (fd, LOCK_EX | LOCK_NB) == 0)
		return (1);
#ifdef DEBUG
	perror ("AcquireLock");
#endif
	return (0);
}


void
ReleaseLock (f)
FILE	*f;
{
int	fd;

	fd = fileno (f);
	(void) flock (fd, LOCK_UN);
}

#endif /* HAS_FLOCK */

#endif /* HAS_FCNTL */
