#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <errno.h>
#include <flock.h>


flock (fd, how)
int    fd,
       how;
{
       int             cmd,
                       ret;
       struct  flock   lck;

#ifdef DEBUG
       printf ("in flock, fd=%d, how=0x%x\n", fd, how);
#endif /* DEBUG */

       if (how & LOCK_NB)              /* want non-blocking */
               cmd = F_SETLK;          /* always returns immediately */
       else
               cmd = F_SETLKW;         /* waits until lock can be done */

       if (how & LOCK_SH)              /* shared usually means reading */
               lck.l_type = F_RDLCK;
       else if (how & LOCK_EX)         /* exclusive -- writing */
               lck.l_type = F_WRLCK;
       else if (how & LOCK_UN)         /* unlock */
               lck.l_type = F_UNLCK;

       lck.l_whence = SEEK_SET;        /* from start of file */
       lck.l_start = 0L;               /* from start of extent */
       lck.l_len = 0L;                 /* to end of file */


       /*
        *      Do the deed.
        */
       ret = fcntl (fd, cmd, &lck);

       /*
        *      if a non-blocking lock was specified and it failed, set errno
        *      to EWOULDBLOCK as BSD does it.
        */
       if (ret == -1 && cmd == F_SETLK && (errno == EACCES || errno == EAGAIN))
               errno = EWOULDBLOCK;

#ifdef DEBUG
       printf ("returning %d.\n", ret);
#endif /* DEBUG */
       return ret;
}
