Back to index

glibc  2.9
lockf64.c
Go to the documentation of this file.
00001 /* Copyright (C) 1994,96,97,98,99,2000 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #include <sys/types.h>
00020 #include <unistd.h>
00021 #include <fcntl.h>
00022 #include <errno.h>
00023 #include <string.h>
00024 
00025 /* lockf is a simplified interface to fcntl's locking facilities.  */
00026 
00027 int
00028 lockf64 (int fd, int cmd, off64_t len64)
00029 {
00030   struct flock fl;
00031   off_t len = (off_t) len64;
00032 
00033   if (len64 != (off64_t) len)
00034     {
00035       /* We can't represent the length.  */
00036       __set_errno (EOVERFLOW);
00037       return -1;
00038     }
00039 
00040   memset ((char *) &fl, '\0', sizeof (fl));
00041 
00042   /* lockf is always relative to the current file position.  */
00043   fl.l_whence = SEEK_CUR;
00044   fl.l_start = 0;
00045   fl.l_len = len;
00046 
00047   switch (cmd)
00048     {
00049     case F_TEST:
00050       /* Test the lock: return 0 if FD is unlocked or locked by this process;
00051         return -1, set errno to EACCES, if another process holds the lock.  */
00052       fl.l_type = F_RDLCK;
00053       if (__fcntl (fd, F_GETLK, &fl) < 0)
00054        return -1;
00055       if (fl.l_type == F_UNLCK || fl.l_pid == __getpid ())
00056        return 0;
00057       __set_errno (EACCES);
00058       return -1;
00059 
00060     case F_ULOCK:
00061       fl.l_type = F_UNLCK;
00062       cmd = F_SETLK;
00063       break;
00064     case F_LOCK:
00065       fl.l_type = F_WRLCK;
00066       cmd = F_SETLKW;
00067       break;
00068     case F_TLOCK:
00069       fl.l_type = F_WRLCK;
00070       cmd = F_SETLK;
00071       break;
00072 
00073     default:
00074       __set_errno (EINVAL);
00075       return -1;
00076     }
00077 
00078   return __fcntl (fd, cmd, &fl);
00079 }