1 .\" Copyright (c) 2000 Jonathan Lemon
2 .\" All rights reserved.
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\" notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\" notice, this list of conditions and the following disclaimer in the
11 .\" documentation and/or other materials provided with the distribution.
13 .\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND
14 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 .Nd kernel event notification mechanism
39 .Fn kqueuex "u_int flags"
43 .Fa "const struct kevent *changelist"
45 .Fa "struct kevent *eventlist"
47 .Fa "const struct timespec *timeout"
49 .Fn EV_SET "kev" ident filter flags fflags data udata
54 provides a generic method of notifying the user when an event
55 happens or a condition holds, based on the results of small
56 pieces of kernel code termed filters.
57 A kevent is identified by the (ident, filter) pair; there may only
58 be one unique kevent per kqueue.
60 The filter is executed upon the initial registration of a kevent
61 in order to detect whether a preexisting condition is present, and is also
62 executed whenever an event is passed to the filter for evaluation.
63 If the filter determines that the condition should be reported,
64 then the kevent is placed on the kqueue for the user to retrieve.
66 The filter is also run when the user attempts to retrieve the kevent
68 If the filter indicates that the condition that triggered
69 the event no longer holds, the kevent is removed from the kqueue and
72 Multiple events which trigger the filter do not result in multiple
73 kevents being placed on the kqueue; instead, the filter will aggregate
74 the events into a single struct kevent.
77 on a file descriptor will remove any kevents that reference the descriptor.
82 creates a new kernel event queue and returns a descriptor.
83 The queue is not inherited by a child created with
89 flag, then the descriptor table is shared,
90 which will allow sharing of the kqueue between two processes.
94 system call also creates a new kernel event queue, and additionally takes
97 argument, which is a bitwise-inclusive OR of the following flags:
98 .Bl -tag -width "KQUEUE_CLOEXEC"
100 The returned file descriptor is automatically closed on
105 call is equivalent to
106 .Ql fd = kqueuex(0) .
108 For compatibility with
112 function is provided, which accepts the
114 flag with the expected semantic.
119 is used to register events with the queue, and return any pending
124 is a pointer to an array of
126 structures, as defined in
128 All changes contained in the
130 are applied before any pending events are read from the queue.
139 is a pointer to an array of kevent structures.
143 determines the size of
149 will return immediately even if there is a
155 is a non-NULL pointer, it specifies a maximum interval to wait
156 for an event, which will be interpreted as a struct timespec.
162 To effect a poll, the
164 argument should be non-NULL, pointing to a zero-valued
167 The same array may be used for the
174 macro is provided for ease of initializing a
179 structure is defined as:
182 uintptr_t ident; /* identifier for this event */
183 short filter; /* filter for event */
184 u_short flags; /* action flags for kqueue */
185 u_int fflags; /* filter flag value */
186 int64_t data; /* filter data value */
187 void *udata; /* opaque user data identifier */
188 uint64_t ext[4]; /* extensions */
195 .Bl -tag -width "Fa filter"
197 Value used to identify this event.
198 The exact interpretation is determined by the attached filter,
199 but often is a file descriptor.
201 Identifies the kernel filter used to process this event.
203 system filters are described below.
205 Actions to perform on the event.
207 Filter-specific flags.
209 Filter-specific data value.
211 Opaque user-defined value passed through the kernel unchanged.
213 Extended data passed to and from kernel.
218 members use is defined by the filter.
219 If the filter does not use them, the members are copied unchanged.
224 members are always passed through the kernel as-is,
225 making additional context available to application.
230 field can contain the following values:
231 .Bl -tag -width EV_DISPATCH
233 Adds the event to the kqueue.
234 Re-adding an existing event
235 will modify the parameters of the original event, and not result
236 in a duplicate entry.
237 Adding an event automatically enables it,
238 unless overridden by the EV_DISABLE flag.
242 to return the event if it is triggered.
247 The filter itself is not disabled.
249 Disable the event source immediately after delivery of an event.
254 Removes the event from the kqueue.
255 Events which are attached to
256 file descriptors are automatically deleted on the last close of
259 This flag is useful for making bulk changes to a kqueue without draining
261 When passed as input, it forces
263 to always be returned.
264 When a filter is successfully added the
267 Note that if this flag is encountered and there is no remaining space in
271 event, then subsequent changes will not get processed.
273 Causes the event to return only the first occurrence of the filter
275 After the user retrieves the event from the kqueue,
278 After the event is retrieved by the user, its state is reset.
279 This is useful for filters which report state transitions
280 instead of the current state.
281 Note that some filters may automatically
282 set this flag internally.
284 Filters may set this flag to indicate filter-specific EOF condition.
292 to leave unchanged any
294 associated with an existing event.
295 This allows other aspects of the event to be modified without requiring the
298 value presently associated.
299 This is especially useful with
303 This flag may not be used with
307 The predefined system filters are listed below.
308 Arguments may be passed to and from the filter via the
312 fields in the kevent structure.
313 .Bl -tag -width "Dv EVFILT_PROCDESC"
315 Takes a descriptor as the identifier, and returns whenever
316 there is data available to read.
317 The behavior of the filter is slightly different depending
318 on the descriptor type.
321 Sockets which have previously been passed to
323 return when there is an incoming connection pending.
325 contains the size of the listen backlog.
327 Other socket descriptors return when there is data to be read,
330 value of the socket buffer.
331 This may be overridden with a per-filter low water mark at the
332 time the filter is added by setting the
336 and specifying the new low water mark in
340 contains the number of bytes of protocol data available to read.
342 If the read direction of the socket has shutdown, then the filter
347 and returns the socket error (if any) in
349 It is possible for EOF to be returned (indicating the connection is gone)
350 while there is still data pending in the socket buffer.
352 Returns when the file pointer is not at the end of file.
354 contains the offset from current position to end of file,
357 This behavior is different from
359 where read events are triggered for regular files unconditionally.
360 This event can be triggered unconditionally by setting the
365 Returns when the there is data to read;
367 contains the number of bytes available.
369 When the last writer disconnects, the filter will set
373 This will be cleared by the filter when a new writer connects,
375 filter will resume waiting for data to become available before
378 Returns when the BPF buffer is full, the BPF timeout has expired, or
381 enabled and there is any data to read;
383 contains the number of bytes available.
385 Returns when the counter is greater than 0;
387 contains the counter value, which must be cast to
390 Returns when pending events are present on the queue;
392 contains the number of events available.
395 Takes a descriptor as the identifier, and returns whenever
396 it is possible to write to the descriptor.
400 will contain the amount of space remaining in the write buffer.
403 when the reader disconnects, and for the fifo case, this will be cleared
404 when a new reader connects.
405 Note that this filter is not supported for vnodes.
407 For sockets, the low water mark and socket error handling is
414 will contain the maximum value that can be added to the counter
417 For BPF devices, when the descriptor is attached to an interface the filter
418 always indicates that it is possible to write and
420 will contain the MTU size of the underlying interface.
422 Takes a descriptor as the identifier, and returns whenever
423 there is no remaining data in the write buffer.
425 Events for this filter are not registered with
427 directly but are registered via the
429 member of an asynchronous I/O request when it is scheduled via an
430 asynchronous I/O system call such as
432 The filter returns under the same conditions as
434 For more details on this filter see
438 Takes a file descriptor as the identifier and the events to watch for in
440 and returns when one or more of the requested events occurs on the descriptor.
441 The events to monitor are:
442 .Bl -tag -width "Dv NOTE_CLOSE_WRITE"
444 The file referenced by the descriptor had its attributes changed.
446 A file descriptor referencing the monitored file, was closed.
447 The closed file descriptor did not have write access.
448 .It Dv NOTE_CLOSE_WRITE
449 A file descriptor referencing the monitored file, was closed.
450 The closed file descriptor had write access.
452 This note, as well as
454 are not activated when files are closed forcibly by
459 is sent for such events.
463 system call was called on the file referenced by the descriptor.
465 For regular file, the file referenced by the descriptor was extended.
467 For directory, reports that a directory entry was added or removed,
468 as the result of rename operation.
471 event is not reported when a name is changed inside the directory.
473 The link count on the file changed.
476 event is reported if a subdirectory was created or deleted inside
477 the directory referenced by the descriptor.
479 The file referenced by the descriptor was opened.
481 A read occurred on the file referenced by the descriptor.
483 The file referenced by the descriptor was renamed.
485 Access to the file was revoked via
487 or the underlying file system was unmounted.
489 A write occurred on the file referenced by the descriptor.
494 contains the events which triggered the filter.
496 Takes the process ID to monitor as the identifier and the events to watch for
499 and returns when the process performs one or more of the requested events.
500 If a process can normally see another process, it can attach an event to it.
501 The events to monitor are:
502 .Bl -tag -width "Dv NOTE_TRACKERR"
504 The process has exited.
505 The exit status will be stored in
507 in the same format as the status returned by
510 The process has called
513 The process has executed a new process via
517 Follow a process across
520 The parent process registers a new kevent to monitor the child process
523 as the original event.
524 The child process will signal an event with
528 and the parent PID in
531 If the parent process fails to register a new kevent
532 .Pq usually due to resource limitations ,
533 it will signal an event with
537 and the child process will not signal a
544 contains the events which triggered the filter.
545 .It Dv EVFILT_PROCDESC
546 Takes the process descriptor created by
548 to monitor as the identifier and the events to watch for in
550 and returns when the associated process performs one or more of the
552 The events to monitor are:
553 .Bl -tag -width "Dv NOTE_EXIT"
555 The process has exited.
556 The exit status will be stored in
562 contains the events which triggered the filter.
564 Takes the signal number to monitor as the identifier and returns
565 when the given signal is delivered to the process.
566 This coexists with the
570 facilities, and has a lower precedence.
571 The filter will record
572 all attempts to deliver a signal to a process, even if the signal has
577 signal, which, if ignored, will not be recorded by the filter.
578 Event notification happens after normal
579 signal delivery processing.
581 returns the number of times the signal has occurred since the last call to
583 This filter automatically sets the
587 Establishes an arbitrary timer identified by
591 specifies the moment to fire the timer (for
593 or the timeout period.
594 The timer will be periodic unless
601 contains the number of times the timeout has expired since the last call to
603 For non-monotonic timers, this filter automatically sets the
607 The filter accepts the following flags in the
610 .Bl -tag -width "Dv NOTE_MSECONDS"
624 The specified expiration time is absolute.
629 is not set, the default is milliseconds.
632 contains the events which triggered the filter.
634 Periodic timers with a specified timeout of 0 will be silently adjusted to
635 timeout after 1 of the time units specified by the requested precision in
637 If an absolute time is specified that has already passed, then it is treated as
638 if the current time were specified and the event will fire as soon as possible.
640 If an existing timer is re-added, the existing timer will be
641 effectively canceled (throwing away any undelivered record of previous
642 timer expiration) and re-started using the new parameters contained in
647 There is a system wide limit on the number of timers
648 which is controlled by the
649 .Va kern.kq_calloutmax
652 Establishes a user event identified by
654 which is not associated with any kernel mechanism but is triggered by
656 The lower 24 bits of the
658 may be used for user defined flags and manipulated using the following:
659 .Bl -tag -width "Dv NOTE_FFLAGSMASK"
672 .It Dv NOTE_FFCTRLMASK
675 .It Dv NOTE_FFLAGSMASK
676 User defined flag mask for
680 A user event is triggered for output with the following:
681 .Bl -tag -width "Dv NOTE_FFLAGSMASK"
683 Cause the event to be triggered.
688 contains the users defined flags in the lower 24 bits.
690 .Sh CANCELLATION BEHAVIOUR
693 is non-zero, i.e., the function is potentially blocking, the call
694 is a cancellation point.
697 is zero, the call is not cancellable.
698 Cancellation can only occur before any changes are made to the kqueue,
699 or when the call was blocked and no changes to the queue were requested.
704 creates a new kernel event queue and returns a file descriptor.
705 If there was an error creating the kernel event queue, a value of -1 is
706 returned and errno set.
711 returns the number of events placed in the
713 up to the value given by
715 If an error occurs while processing an element of the
717 and there is enough room in the
719 then the event will be placed in the
725 and the system error in
729 will be returned, and
731 will be set to indicate the error condition.
732 If the time limit expires, then
736 .Bd -literal -compact
737 #include <sys/event.h>
745 main(int argc, char **argv)
747 struct kevent event; /* Event we want to monitor */
748 struct kevent tevent; /* Event triggered */
752 err(EXIT_FAILURE, "Usage: %s path\en", argv[0]);
753 fd = open(argv[1], O_RDONLY);
755 err(EXIT_FAILURE, "Failed to open '%s'", argv[1]);
760 err(EXIT_FAILURE, "kqueue() failed");
762 /* Initialize kevent structure. */
763 EV_SET(&event, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE,
765 /* Attach event to the kqueue. */
766 ret = kevent(kq, &event, 1, NULL, 0, NULL);
768 err(EXIT_FAILURE, "kevent register");
771 /* Sleep until something happens. */
772 ret = kevent(kq, NULL, 0, &tevent, 1, NULL);
774 err(EXIT_FAILURE, "kevent wait");
775 } else if (ret > 0) {
776 if (tevent.flags & EV_ERROR)
777 errx(EXIT_FAILURE, "Event error: %s", strerror(event.data));
779 printf("Something was written in '%s'\en", argv[1]);
783 /* kqueues are destroyed upon close() */
791 system call fails if:
794 The kernel failed to allocate enough memory for the kernel queue.
801 for the current user would be exceeded.
803 The per-process descriptor table is full.
805 The system file table is full.
810 system call fails if:
813 The process does not have permission to register a filter.
815 There was an error reading or writing the
819 The specified descriptor is invalid.
821 A signal was delivered before the timeout expired and before any
822 events were placed on the kqueue for return.
824 A cancellation request was delivered to the thread, but not yet handled.
826 The specified time limit or filter is invalid.
828 The specified length of the event or change lists is negative.
830 The event could not be found to be modified or deleted.
832 No memory was available to register the event
833 or, in the special case of a timer, the maximum number of
834 timers has been exceeded.
835 This maximum is configurable via the
836 .Va kern.kq_calloutmax
839 The specified process to attach to does not exist.
846 error, all changes in the
858 .Xr pthread_setcancelstate 3 ,
862 .%T "Kqueue: A Generic and Scalable Event Notification Facility"
863 .%I USENIX Association
864 .%B Proceedings of the FREENIX Track: 2001 USENIX Annual Technical Conference
866 .\".http://www.usenix.org/event/usenix01/freenix01/full_papers/lemon/lemon.pdf
873 system calls first appeared in
878 system and this manual page were written by
879 .An Jonathan Lemon Aq Mt jlemon@FreeBSD.org .
882 In versions older than
885 failed to parse without including