kevent behavior

Jilles Tjoelker jilles at stack.nl
Tue Mar 24 22:15:45 UTC 2015


On Thu, Mar 19, 2015 at 07:33:06AM +0100, Ivan Radovanovic wrote:
> Is there defined (and guaranteed) behavior of kevent if kqueue FD is 
> being closed while blocking kevent call is in progress?

> Possible scenario would be like this:

> Thread 1:
> ...
> kfd = kqueue();
> ...
> // create second thread afterwords
> // and do blocking wait for events
> result = kevent(kfd, changelist, nchanges, eventlist, nevents, NULL);
> if (result == -1)
> 	// check if there was request to stop listening for events

> Thread 2:
> // do something
> // then close kqueue's fd
> close(kfd);

> I am asking this because file watcher implementation for mono is 
> implemented that way (which I find nicer than using timeout), but this 
> is apparently based on expected kevent behavior under Darwin, and I 
> can't find any mention that in FreeBSD kevent is going to behave the 
> same way (at least not on kqueue(2) manual page)

This method is inherently unsafe, since you cannot be sure thread 1 has
started blocking in kevent() when you close() in thread 2. If not, there
might be a thread 3 creating a kqueue between thread 2's close and
thread 1's kevent, and thread 1 will manipulate the new kqueue.

Fortunately, EVFILT_USER provides an easy way to wake up a thread
blocked in kevent().

If kevent() was implemented as a cancellation point, pthread_cancel()
would be another option, but it is not.

-- 
Jilles Tjoelker


More information about the freebsd-hackers mailing list