Skip to content
Advertisement

inotify_add_watch relative to O_PATH dirfd

I am trying to call inotify_add_watch to watch a file. I would like to specify the file relative to an O_PATH | O_DIRECTORY file descriptor, a la symlinkat, fstatat, or openat.

Is this possible? It doesn’t look like it is. Anyone know of a workaround?

EDIT

The closest thing seems to be the “trick” described at man 2 open under “Rationale for openat”. See the answer by user1643723 for an example.

Advertisement

Answer

You can use symlinks, provided by procfs to achieve the functionality of most *at calls. Open a directory descriptor and use /proc/self/fd/<dir descriptor>/filename instead of the full path to filename:

#define _GNU_SOURCE

#include <sys/stat.h>
#include <sys/inotify.h>
#include <sys/types.h>

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main() {
    int inotify = inotify_init();

    mkdir("tmp", 0777);
    mknod("tmp/foo", 0777 | S_IFREG, 0);

    int dirFd = open("tmp", O_DIRECTORY | O_PATH);

    char buf[40] = { '' };

    sprintf(buf, "/proc/self/fd/%d/foo", dirFd);

    int watchd = inotify_add_watch(inotify, buf, IN_MOVE | IN_ATTRIB);

    if (watchd < 0) {
        printf("Failed: %s", strerror(errno));
    } else {
        printf("ok");
    }
}

The program above prints “ok” on Linux 4.4.x.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement