Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Test inotify on memfd with epoll api
#include <stdio.h>
#include <sys/inotify.h>
#include <sys/time.h>
#include <sys/epoll.h>
#include <errno.h>
#include <linux/memfd.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef __NR_memfd_create // older glibc may not have this syscall defined
#define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
// Note that linux must be 3.17 or greater to support this
int memfd_create(const char *name, unsigned int flags) {
return syscall(__NR_memfd_create, name, flags);
}
#endif
int inotify_init(void);
int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
int main(int argc, char** argv)
{
char buf[64];
fd_set set;
struct timeval timeout;
FD_ZERO (&set);
int fd = memfd_create("/foo", F_SEAL_SEAL);
sprintf(buf, "/proc/self/fd/%d", fd);
int inotify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (inotify < 0) {
printf("Err inotify_init1\n");
return 1;
}
//uint32_t mask = IN_DELETE | IN_MODIFY | IN_MOVE | IN_ONLYDIR | IN_MOVE_SELF |
// IN_DELETE_SELF;
int ret = inotify_add_watch(inotify, buf, IN_MODIFY);
int epollfd = epoll_create1(EPOLL_CLOEXEC);
if (epollfd < 0) {
printf("ERR epoll_creat1\n");
return 1;
}
// Add inotifyfd to epoll set
struct epoll_event ev;
//std::memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.fd = inotify;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, inotify, &ev) < 0) {
printf("ERR epoll_ctl\n"); //<< ::strerror_r(errno, buf, sizeof(buf));
return 1;
}
int kMaxEvents = 10;
struct epoll_event events[kMaxEvents];
int n;
do {
n = epoll_wait(epollfd, events, kMaxEvents, -1);
} while (n < 0 && errno == EINTR);
char dbuf[1024];
for (int i = 0; i < n; ++i) {
int ifd = events[i].data.fd;
read(fd, dbuf, sizeof(dbuf));
printf("Read %s from %d\n", dbuf, fd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.