/*
 * File:        lock.c
 *
 * Author:      Ulli Horlacher (framstag@belwue.de)
 *
 * History:
 *
 *   1998-05-10	Framstag	moved from sendfiled.c
 *
 * These are functions which sets or tests advisory locks conforming to POSIX 
 * fcntl() call.
 *
 * Copyright © 1998 Ulli Horlacher
 * This file is covered by the GNU General Public License
 */

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


/*
 * wlock_file - write-lock a file (POSIX conform)
 *
 * INPUT:  file descriptor
 *
 * RETURN: >= 0 if ok, -1 if error
 */
int wlock_file(int fd) {
  struct flock lock;	/* file locking structure */

  /* fill out the file locking structure */
  lock.l_type=F_WRLCK;
  lock.l_start=0;
  lock.l_whence=SEEK_SET;
  lock.l_len=0;

  /* try to lock the file and return the status */
  return(fcntl(fd,F_SETLK,&lock));
}


/*
 * tlock_file - test if a file is write-lock blocked (POSIX conform)
 *
 * INPUT:  fd  - file descriptor
 *
 * RETURN: 0 if no lock, 1 if locked, -1 on error
 */
int tlock_file(int fd) {
  int status;
  struct flock lock;    /* file locking structure */

  /* fill out the file locking structure */
  lock.l_type=F_WRLCK;
  lock.l_start=0;
  lock.l_whence=SEEK_SET;
  lock.l_len=0;

  /* test the lock status */
  status=fcntl(fd,F_GETLK,&lock);
  if (status>=0) status=(lock.l_type!=F_UNLCK);
  return(status);
}


syntax highlighted by Code2HTML, v. 0.9.1