1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include "fd-util.h"
4 #include "inotify-util.h"
5 #include "stat-util.h"
6 
inotify_add_watch_fd(int fd,int what,uint32_t mask)7 int inotify_add_watch_fd(int fd, int what, uint32_t mask) {
8         int wd, r;
9 
10         /* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
11         wd = inotify_add_watch(fd, FORMAT_PROC_FD_PATH(what), mask);
12         if (wd < 0) {
13                 if (errno != ENOENT)
14                         return -errno;
15 
16                 /* Didn't work with ENOENT? If so, then either /proc/ isn't mounted, or the fd is bad */
17                 r = proc_mounted();
18                 if (r == 0)
19                         return -ENOSYS;
20                 if (r > 0)
21                         return -EBADF;
22 
23                 return -ENOENT; /* OK, no clue, let's propagate the original error */
24         }
25 
26         return wd;
27 }
28 
inotify_add_watch_and_warn(int fd,const char * pathname,uint32_t mask)29 int inotify_add_watch_and_warn(int fd, const char *pathname, uint32_t mask) {
30         int wd;
31 
32         wd = inotify_add_watch(fd, pathname, mask);
33         if (wd < 0) {
34                 if (errno == ENOSPC)
35                         return log_error_errno(errno, "Failed to add a watch for %s: inotify watch limit reached", pathname);
36 
37                 return log_error_errno(errno, "Failed to add a watch for %s: %m", pathname);
38         }
39 
40         return wd;
41 }
42