lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* Copyright (C) 1994, 1996, 1997, 1998, 2000 Free Software Foundation, Inc. |
| 2 | This file is part of the GNU C Library. |
| 3 | |
| 4 | The GNU C Library is free software; you can redistribute it and/or |
| 5 | modify it under the terms of the GNU Library General Public License as |
| 6 | published by the Free Software Foundation; either version 2 of the |
| 7 | License, or (at your option) any later version. |
| 8 | |
| 9 | The GNU C Library is distributed in the hope that it will be useful, |
| 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 | Library General Public License for more details. |
| 13 | |
| 14 | You should have received a copy of the GNU Library General Public |
| 15 | License along with the GNU C Library; see the file COPYING.LIB. If not, |
| 16 | write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, |
| 17 | Boston, MA 02111-1307, USA. */ |
| 18 | |
| 19 | #include <features.h> |
| 20 | |
| 21 | #include <sys/types.h> |
| 22 | #include <unistd.h> |
| 23 | #include <fcntl.h> |
| 24 | #include <errno.h> |
| 25 | #include <string.h> |
| 26 | |
| 27 | |
| 28 | |
| 29 | /* lockf is a simplified interface to fcntl's locking facilities. */ |
| 30 | |
| 31 | int lockf (int fd, int cmd, off_t len) |
| 32 | { |
| 33 | struct flock fl; |
| 34 | |
| 35 | memset ((char *) &fl, '\0', sizeof (fl)); |
| 36 | |
| 37 | /* lockf is always relative to the current file position. */ |
| 38 | fl.l_whence = SEEK_CUR; |
| 39 | fl.l_start = 0; |
| 40 | fl.l_len = len; |
| 41 | |
| 42 | switch (cmd) |
| 43 | { |
| 44 | case F_TEST: |
| 45 | /* Test the lock: return 0 if FD is unlocked or locked by this process; |
| 46 | return -1, set errno to EACCES, if another process holds the lock. */ |
| 47 | fl.l_type = F_RDLCK; |
| 48 | if (fcntl (fd, F_GETLK, &fl) < 0) |
| 49 | return -1; |
| 50 | if (fl.l_type == F_UNLCK || fl.l_pid == getpid ()) |
| 51 | return 0; |
| 52 | __set_errno(EACCES); |
| 53 | return -1; |
| 54 | |
| 55 | case F_ULOCK: |
| 56 | fl.l_type = F_UNLCK; |
| 57 | cmd = F_SETLK; |
| 58 | break; |
| 59 | case F_LOCK: |
| 60 | fl.l_type = F_WRLCK; |
| 61 | cmd = F_SETLKW; |
| 62 | break; |
| 63 | case F_TLOCK: |
| 64 | fl.l_type = F_WRLCK; |
| 65 | cmd = F_SETLK; |
| 66 | break; |
| 67 | |
| 68 | default: |
| 69 | __set_errno(EINVAL); |
| 70 | return -1; |
| 71 | } |
| 72 | |
| 73 | return fcntl(fd, cmd, &fl); |
| 74 | } |
| 75 | libc_hidden_def(lockf) |