macosbsdkqueue

What is the required lifetime of struct kevent passed into kevent changelist?


The signature of the kevent system call for OSX and BSD is as follows:

     int
     kevent(int kq, const struct kevent *changelist, int nchanges, struct kevent *eventlist,
         int nevents, const struct timespec *timeout);

Suppose I have an invocation like the following:

  struct kevent kqueue_event;
  EV_SET(&kqueue_event, fd_to_add, EVFILT_READ, EV_ADD, 0, /*data=*/0, NULL);

  kevent(watcher_fd, &kqueue_event, 1, NULL, 0, NULL);

If the above invocation is inside a function, the kqueue_event structure will go out of scope as soon as the function returns.

Given that I just passed a pointer to this structure into the kevent function, is this going to cause problems for me down the road, or is the structure no longer needed after kevent returns?

The man page does not appear to say anything about how long the array needs to stick around.


Solution

  • It seems you can forget and don't care about the changelist passed after the successful kevent() call.

    Take a look here https://github.com/apple/darwin-xnu/blob/main/bsd/kern/kern_event.c at kevent_internal function.

    What they do there, they call kevent_modern_copyin (or legacy_copyin), both with copyin inside, so this structure is copied into kernel memory, and lives there now.