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 ZoL 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.
19 #include <sys/resource.h>
21 #include <sys/types.h>
27 * Read up to [n] bytes from [fd] into [buf].
28 * Return the number of bytes read, 0 on EOF, or -1 on error.
31 zed_file_read_n(int fd
, void *buf
, size_t n
)
40 if ((n_read
= read(fd
, p
, n_left
)) < 0) {
46 } else if (n_read
== 0) {
56 * Write [n] bytes from [buf] out to [fd].
57 * Return the number of bytes written, or -1 on error.
60 zed_file_write_n(int fd
, void *buf
, size_t n
)
62 const unsigned char *p
;
69 if ((n_written
= write(fd
, p
, n_left
)) < 0) {
83 * Set an exclusive advisory lock on the open file descriptor [fd].
84 * Return 0 on success, 1 if a conflicting lock is held by another process,
85 * or -1 on error (with errno set).
96 lock
.l_type
= F_WRLCK
;
97 lock
.l_whence
= SEEK_SET
;
101 if (fcntl(fd
, F_SETLK
, &lock
) < 0) {
102 if ((errno
== EACCES
) || (errno
== EAGAIN
))
111 * Release an advisory lock held on the open file descriptor [fd].
112 * Return 0 on success, or -1 on error (with errno set).
115 zed_file_unlock(int fd
)
123 lock
.l_type
= F_UNLCK
;
124 lock
.l_whence
= SEEK_SET
;
128 if (fcntl(fd
, F_SETLK
, &lock
) < 0)
135 * Test whether an exclusive advisory lock could be obtained for the open
136 * file descriptor [fd].
137 * Return 0 if the file is not locked, >0 for the PID of another process
138 * holding a conflicting lock, or -1 on error (with errno set).
141 zed_file_is_locked(int fd
)
149 lock
.l_type
= F_WRLCK
;
150 lock
.l_whence
= SEEK_SET
;
154 if (fcntl(fd
, F_GETLK
, &lock
) < 0)
157 if (lock
.l_type
== F_UNLCK
)
164 * Close all open file descriptors greater than or equal to [lowfd].
165 * Any errors encountered while closing file descriptors are ignored.
168 zed_file_close_from(int lowfd
)
170 const int maxfd_def
= 256;
178 if (getrlimit(RLIMIT_NOFILE
, &rl
) < 0) {
180 } else if (rl
.rlim_max
== RLIM_INFINITY
) {
185 for (fd
= lowfd
; fd
< maxfd
; fd
++)
192 * Set the CLOEXEC flag on file descriptor [fd] so it will be automatically
193 * closed upon successful execution of one of the exec functions.
194 * Return 0 on success, or -1 on error.
196 * FIXME: No longer needed?
199 zed_file_close_on_exec(int fd
)
207 flags
= fcntl(fd
, F_GETFD
);
213 if (fcntl(fd
, F_SETFD
, flags
) == -1)