남관우
남관우

Reputation: 31

I have questions about inotify_add_watch that read events

I don't understand the progress of inotify events. I know that inotify_init is to create new inotify instatance. and it returns file descriptor. at this time. for what is file descriptor about?

In my code, the function, inotify_add_watch like below

wd = inotify_add_watch ( inotifyFd, argv[j], IN_ALL_EVENTS),

is called in for the loop.

If I input 2 more files in command, this loop will be repeated 2 times more. and then variable wd will be OVERWRITED. and intofiyFd always has same number. becuase these are not array. then, How can it differentiate 2 more files?

I already learned about

int main (int argc, char *argv[])
{

  int inotifyFd, wd, j;
  char buf[BUF_LEN];
  ssize_t numRead;
  char *p;
  struct inotify_event *event;

  inotifyFd = inotify_init();

  for(j = 1; j < argc; j++)
  {
      wd = inotify_add_watch(inotifyFd, argv[j], IN_ALL_EVENTS);
      printf("Watching %s using wd %d\n", argv[j],  wd);
  }

  for(;;)
  {
      numRead = read(inotifyFd, buf, BUF_LEN);
      if(numRead == 0)
          fatal("read() from inotify fd returned 0!");

      printf("Read %ld bytes from inotify fd\n", (long) numRead);

      for( p = buf; p < buf+numRead; )
      {
          event = (struct  inotify_event *) p;
          displayInotifyEvent(event);

          p+= sizeof(struct inotify_event) + event->len;
      }
  }

  return 0;
}

.

./demoinotify dir1 dir2 &
[1] 5386
Watching dir1 using wd1
watching dir2 using wd2

Upvotes: 0

Views: 760

Answers (1)

user10678532
user10678532

Reputation:

inotify_init() is to create new inotify instatance. and it returns file descriptor. at this time. for what is file descriptor about?

It returns an special file descriptor, which does not refer to any real file in the file system. Just like pipe(), epoll_create(), etc. You use that file to read inotify events from it. It's also pollable.

wd = inotify_add_watch ( inotifyFd, argv[j], IN_ALL_EVENTS), is called in for the loop. If I input 2 more files in command, this loop will be repeated 2 times more. and then variable wd will be OVERWRITED.

Don't overwrite it then. Save its return values into an array.

int *wd = calloc(argc, sizeof *wd);
...
wd[j] = inotify_add_watch(inotifyFd, argv[j], ...);

Notice that the return value of inotify_add_watch is not a file descriptor, but a watch descriptor [1].

How can it differentiate 2 more files?

Compare the wd field from inotify_event you read from the inotify file descriptor with the return value of inotify_add_watch you saved above.

[1] If you look into the /proc/PID/fdinfo/FD, where FD is your inotifyFd, you'll see all the watch descriptors associated with it listed. The format is documented in the proc(5) manpage.

Upvotes: 1

Related Questions