2 * This file is part of the ZFS Event Daemon (ZED).
4 * Developed at Lawrence Livermore National Laboratory (LLNL-CODE-403049).
5 * Copyright (C) 2013-2014 Lawrence Livermore National Security, LLC.
6 * Refer to the OpenZFS git commit log for authoritative copyright attribution.
8 * The contents of this file are subject to the terms of the
9 * Common Development and Distribution License Version 1.0 (CDDL-1.0).
10 * You can obtain a copy of the license from the top-level file
11 * "OPENSOLARIS.LICENSE" or at <http://opensource.org/licenses/CDDL-1.0>.
12 * You may not use this file except in compliance with the license.
21 #include <sys/types.h>
27 * Set an exclusive advisory lock on the open file descriptor [fd].
28 * Return 0 on success, 1 if a conflicting lock is held by another process,
29 * or -1 on error (with errno set).
40 lock
.l_type
= F_WRLCK
;
41 lock
.l_whence
= SEEK_SET
;
45 if (fcntl(fd
, F_SETLK
, &lock
) < 0) {
46 if ((errno
== EACCES
) || (errno
== EAGAIN
))
55 * Release an advisory lock held on the open file descriptor [fd].
56 * Return 0 on success, or -1 on error (with errno set).
59 zed_file_unlock(int fd
)
67 lock
.l_type
= F_UNLCK
;
68 lock
.l_whence
= SEEK_SET
;
72 if (fcntl(fd
, F_SETLK
, &lock
) < 0)
79 * Test whether an exclusive advisory lock could be obtained for the open
80 * file descriptor [fd].
81 * Return 0 if the file is not locked, >0 for the PID of another process
82 * holding a conflicting lock, or -1 on error (with errno set).
85 zed_file_is_locked(int fd
)
93 lock
.l_type
= F_WRLCK
;
94 lock
.l_whence
= SEEK_SET
;
98 if (fcntl(fd
, F_GETLK
, &lock
) < 0)
101 if (lock
.l_type
== F_UNLCK
)
109 #define PROC_SELF_FD "/dev/fd"
110 #else /* Linux-compatible layout */
111 #define PROC_SELF_FD "/proc/self/fd"
115 * Close all open file descriptors greater than or equal to [lowfd].
116 * Any errors encountered while closing file descriptors are ignored.
119 zed_file_close_from(int lowfd
)
121 int errno_bak
= errno
;
125 struct dirent
*fdent
;
127 if ((fddir
= opendir(PROC_SELF_FD
)) != NULL
) {
128 while ((fdent
= readdir(fddir
)) != NULL
) {
129 fd
= atoi(fdent
->d_name
);
130 if (fd
> maxfd
&& fd
!= dirfd(fddir
))
133 (void) closedir(fddir
);
135 maxfd
= sysconf(_SC_OPEN_MAX
);
137 for (fd
= lowfd
; fd
< maxfd
; fd
++)