]>
git.proxmox.com Git - mirror_zfs.git/blob - cmd/zed/zed_file.c
2 * This file is part of the ZFS Event Daemon (ZED)
3 * for ZFS on Linux (ZoL) <http://zfsonlinux.org/>.
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>
26 * Read up to [n] bytes from [fd] into [buf].
27 * Return the number of bytes read, 0 on EOF, or -1 on error.
30 zed_file_read_n(int fd
, void *buf
, size_t n
)
39 if ((n_read
= read(fd
, p
, n_left
)) < 0) {
45 } else if (n_read
== 0) {
55 * Write [n] bytes from [buf] out to [fd].
56 * Return the number of bytes written, or -1 on error.
59 zed_file_write_n(int fd
, void *buf
, size_t n
)
61 const unsigned char *p
;
68 if ((n_written
= write(fd
, p
, n_left
)) < 0) {
82 * Set an exclusive advisory lock on the open file descriptor [fd].
83 * Return 0 on success, 1 if a conflicting lock is held by another process,
84 * or -1 on error (with errno set).
95 lock
.l_type
= F_WRLCK
;
96 lock
.l_whence
= SEEK_SET
;
100 if (fcntl(fd
, F_SETLK
, &lock
) < 0) {
101 if ((errno
== EACCES
) || (errno
== EAGAIN
))
110 * Release an advisory lock held on the open file descriptor [fd].
111 * Return 0 on success, or -1 on error (with errno set).
114 zed_file_unlock(int fd
)
122 lock
.l_type
= F_UNLCK
;
123 lock
.l_whence
= SEEK_SET
;
127 if (fcntl(fd
, F_SETLK
, &lock
) < 0)
134 * Test whether an exclusive advisory lock could be obtained for the open
135 * file descriptor [fd].
136 * Return 0 if the file is not locked, >0 for the PID of another process
137 * holding a conflicting lock, or -1 on error (with errno set).
140 zed_file_is_locked(int fd
)
148 lock
.l_type
= F_WRLCK
;
149 lock
.l_whence
= SEEK_SET
;
153 if (fcntl(fd
, F_GETLK
, &lock
) < 0)
156 if (lock
.l_type
== F_UNLCK
)
163 * Close all open file descriptors greater than or equal to [lowfd].
164 * Any errors encountered while closing file descriptors are ignored.
167 zed_file_close_from(int lowfd
)
169 const int maxfd_def
= 256;
177 if (getrlimit(RLIMIT_NOFILE
, &rl
) < 0) {
179 } else if (rl
.rlim_max
== RLIM_INFINITY
) {
184 for (fd
= lowfd
; fd
< maxfd
; fd
++)
191 * Set the CLOEXEC flag on file descriptor [fd] so it will be automatically
192 * closed upon successful execution of one of the exec functions.
193 * Return 0 on success, or -1 on error.
195 * FIXME: No longer needed?
198 zed_file_close_on_exec(int fd
)
206 flags
= fcntl(fd
, F_GETFD
);
212 if (fcntl(fd
, F_SETFD
, flags
) == -1)