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
33 .Nd kernel event notification mechanism
41 .Fn kevent "int kq" "const struct kevent *changelist" "int nchanges" "struct kevent *eventlist" "int nevents" "const struct timespec *timeout"
42 .Fn EV_SET "kev" ident filter flags fflags data udata
47 provides a generic method of notifying the user when an event
48 happens or a condition holds, based on the results of small
49 pieces of kernel code termed filters.
50 A kevent is identified by the (ident, filter) pair; there may only
51 be one unique kevent per kqueue.
53 The filter is executed upon the initial registration of a kevent
54 in order to detect whether a preexisting condition is present, and is also
55 executed whenever an event is passed to the filter for evaluation.
56 If the filter determines that the condition should be reported,
57 then the kevent is placed on the kqueue for the user to retrieve.
59 The filter is also run when the user attempts to retrieve the kevent
61 If the filter indicates that the condition that triggered
62 the event no longer holds, the kevent is removed from the kqueue and
65 Multiple events which trigger the filter do not result in multiple
66 kevents being placed on the kqueue; instead, the filter will aggregate
67 the events into a single struct kevent.
70 on a file descriptor will remove any kevents that reference the descriptor.
75 creates a new kernel event queue and returns a descriptor.
76 The queue is not inherited by a child created with
82 flag, then the descriptor table is shared,
83 which will allow sharing of the kqueue between two processes.
88 is used to register events with the queue, and return any pending
93 is a pointer to an array of
95 structures, as defined in
97 All changes contained in the
99 are applied before any pending events are read from the queue.
108 is a pointer to an array of kevent structures.
112 determines the size of
118 will return immediately even if there is a
124 is a non-NULL pointer, it specifies a maximum interval to wait
125 for an event, which will be interpreted as a struct timespec.
131 To effect a poll, the
133 argument should be non-NULL, pointing to a zero-valued
136 The same array may be used for the
143 macro is provided for ease of initializing a
148 structure is defined as:
151 uintptr_t ident; /* identifier for this event */
152 short filter; /* filter for event */
153 u_short flags; /* action flags for kqueue */
154 u_int fflags; /* filter flag value */
155 int64_t data; /* filter data value */
156 void *udata; /* opaque user data identifier */
157 uint64_t ext[4]; /* extensions */
164 .Bl -tag -width "Fa filter"
166 Value used to identify this event.
167 The exact interpretation is determined by the attached filter,
168 but often is a file descriptor.
170 Identifies the kernel filter used to process this event.
172 system filters are described below.
174 Actions to perform on the event.
176 Filter-specific flags.
178 Filter-specific data value.
180 Opaque user-defined value passed through the kernel unchanged.
182 Extended data passed to and from kernel.
187 members use is defined by the filter.
188 If the filter does not use them, the members are copied unchanged.
193 members are always passed through the kernel as-is,
194 making additional context available to application.
199 field can contain the following values:
200 .Bl -tag -width EV_DISPATCH
202 Adds the event to the kqueue.
203 Re-adding an existing event
204 will modify the parameters of the original event, and not result
205 in a duplicate entry.
206 Adding an event automatically enables it,
207 unless overridden by the EV_DISABLE flag.
211 to return the event if it is triggered.
216 The filter itself is not disabled.
218 Disable the event source immediately after delivery of an event.
223 Removes the event from the kqueue.
224 Events which are attached to
225 file descriptors are automatically deleted on the last close of
228 This flag is useful for making bulk changes to a kqueue without draining
230 When passed as input, it forces
232 to always be returned.
233 When a filter is successfully added the
236 Note that if this flag is encountered and there is no remaining space in
240 event, then subsequent changes will not get processed.
242 Causes the event to return only the first occurrence of the filter
244 After the user retrieves the event from the kqueue,
247 After the event is retrieved by the user, its state is reset.
248 This is useful for filters which report state transitions
249 instead of the current state.
250 Note that some filters may automatically
251 set this flag internally.
253 Filters may set this flag to indicate filter-specific EOF condition.
260 The predefined system filters are listed below.
261 Arguments may be passed to and from the filter via the
265 fields in the kevent structure.
266 .Bl -tag -width "Dv EVFILT_PROCDESC"
268 Takes a descriptor as the identifier, and returns whenever
269 there is data available to read.
270 The behavior of the filter is slightly different depending
271 on the descriptor type.
274 Sockets which have previously been passed to
276 return when there is an incoming connection pending.
278 contains the size of the listen backlog.
280 Other socket descriptors return when there is data to be read,
283 value of the socket buffer.
284 This may be overridden with a per-filter low water mark at the
285 time the filter is added by setting the
289 and specifying the new low water mark in
293 contains the number of bytes of protocol data available to read.
295 If the read direction of the socket has shutdown, then the filter
300 and returns the socket error (if any) in
302 It is possible for EOF to be returned (indicating the connection is gone)
303 while there is still data pending in the socket buffer.
305 Returns when the file pointer is not at the end of file.
307 contains the offset from current position to end of file,
310 This behavior is different from
312 where read events are triggered for regular files unconditionally.
313 This event can be triggered unconditionally by setting the
318 Returns when the there is data to read;
320 contains the number of bytes available.
322 When the last writer disconnects, the filter will set
326 This will be cleared by the filter when a new writer connects,
328 filter will resume waiting for data to become available before
331 Returns when the BPF buffer is full, the BPF timeout has expired, or
334 enabled and there is any data to read;
336 contains the number of bytes available.
339 Takes a descriptor as the identifier, and returns whenever
340 it is possible to write to the descriptor.
344 will contain the amount of space remaining in the write buffer.
347 when the reader disconnects, and for the fifo case, this will be cleared
348 when a new reader connects.
349 Note that this filter is not supported for vnodes or BPF devices.
351 For sockets, the low water mark and socket error handling is
356 Takes a descriptor as the identifier, and returns whenever
357 there is no remaining data in the write buffer.
359 Events for this filter are not registered with
361 directly but are registered via the
363 member of an asynchronous I/O request when it is scheduled via an
364 asynchronous I/O system call such as
366 The filter returns under the same conditions as
368 For more details on this filter see
372 Takes a file descriptor as the identifier and the events to watch for in
374 and returns when one or more of the requested events occurs on the descriptor.
375 The events to monitor are:
376 .Bl -tag -width "Dv NOTE_CLOSE_WRITE"
378 The file referenced by the descriptor had its attributes changed.
380 A file descriptor referencing the monitored file, was closed.
381 The closed file descriptor did not have write access.
382 .It Dv NOTE_CLOSE_WRITE
383 A file descriptor referencing the monitored file, was closed.
384 The closed file descriptor had write access.
386 This note, as well as
388 are not activated when files are closed forcibly by
393 is sent for such events.
397 system call was called on the file referenced by the descriptor.
399 For regular file, the file referenced by the descriptor was extended.
401 For directory, reports that a directory entry was added or removed,
402 as the result of rename operation.
405 event is not reported when a name is changed inside the directory.
407 The link count on the file changed.
410 event is reported if a subdirectory was created or deleted inside
411 the directory referenced by the descriptor.
413 The file referenced by the descriptor was opened.
415 A read occurred on the file referenced by the descriptor.
417 The file referenced by the descriptor was renamed.
419 Access to the file was revoked via
421 or the underlying file system was unmounted.
423 A write occurred on the file referenced by the descriptor.
428 contains the events which triggered the filter.
430 Takes the process ID to monitor as the identifier and the events to watch for
433 and returns when the process performs one or more of the requested events.
434 If a process can normally see another process, it can attach an event to it.
435 The events to monitor are:
436 .Bl -tag -width "Dv NOTE_TRACKERR"
438 The process has exited.
439 The exit status will be stored in
442 The process has called
445 The process has executed a new process via
449 Follow a process across
452 The parent process registers a new kevent to monitor the child process
455 as the original event.
456 The child process will signal an event with
460 and the parent PID in
463 If the parent process fails to register a new kevent
464 .Pq usually due to resource limitations ,
465 it will signal an event with
469 and the child process will not signal a
476 contains the events which triggered the filter.
477 .It Dv EVFILT_PROCDESC
478 Takes the process descriptor created by
480 to monitor as the identifier and the events to watch for in
482 and returns when the associated process performs one or more of the
484 The events to monitor are:
485 .Bl -tag -width "Dv NOTE_EXIT"
487 The process has exited.
488 The exit status will be stored in
494 contains the events which triggered the filter.
496 Takes the signal number to monitor as the identifier and returns
497 when the given signal is delivered to the process.
498 This coexists with the
502 facilities, and has a lower precedence.
503 The filter will record
504 all attempts to deliver a signal to a process, even if the signal has
509 signal, which, if ignored, will not be recorded by the filter.
510 Event notification happens after normal
511 signal delivery processing.
513 returns the number of times the signal has occurred since the last call to
515 This filter automatically sets the
519 Establishes an arbitrary timer identified by
523 specifies the moment to fire the timer (for
525 or the timeout period.
526 The timer will be periodic unless
533 contains the number of times the timeout has expired since the last call to
535 For non-monotonic timers, this filter automatically sets the
539 The filter accepts the following flags in the
542 .Bl -tag -width "Dv NOTE_MSECONDS"
556 The specified expiration time is absolute.
561 is not set, the default is milliseconds.
564 contains the events which triggered the filter.
566 If an existing timer is re-added, the existing timer will be
567 effectively canceled (throwing away any undelivered record of previous
568 timer expiration) and re-started using the new parameters contained in
573 There is a system wide limit on the number of timers
574 which is controlled by the
575 .Va kern.kq_calloutmax
578 Establishes a user event identified by
580 which is not associated with any kernel mechanism but is triggered by
582 The lower 24 bits of the
584 may be used for user defined flags and manipulated using the following:
585 .Bl -tag -width "Dv NOTE_FFLAGSMASK"
598 .It Dv NOTE_FFCTRLMASK
601 .It Dv NOTE_FFLAGSMASK
602 User defined flag mask for
606 A user event is triggered for output with the following:
607 .Bl -tag -width "Dv NOTE_FFLAGSMASK"
609 Cause the event to be triggered.
614 contains the users defined flags in the lower 24 bits.
616 .Sh CANCELLATION BEHAVIOUR
619 is non-zero, i.e., the function is potentially blocking, the call
620 is a cancellation point.
623 is zero, the call is not cancellable.
624 Cancellation can only occur before any changes are made to the kqueue,
625 or when the call was blocked and no changes to the queue were requested.
630 creates a new kernel event queue and returns a file descriptor.
631 If there was an error creating the kernel event queue, a value of -1 is
632 returned and errno set.
637 returns the number of events placed in the
639 up to the value given by
641 If an error occurs while processing an element of the
643 and there is enough room in the
645 then the event will be placed in the
651 and the system error in
655 will be returned, and
657 will be set to indicate the error condition.
658 If the time limit expires, then
662 .Bd -literal -compact
663 #include <sys/event.h>
671 main(int argc, char **argv)
673 struct kevent event; /* Event we want to monitor */
674 struct kevent tevent; /* Event triggered */
678 err(EXIT_FAILURE, "Usage: %s path\en", argv[0]);
679 fd = open(argv[1], O_RDONLY);
681 err(EXIT_FAILURE, "Failed to open '%s'", argv[1]);
686 err(EXIT_FAILURE, "kqueue() failed");
688 /* Initialize kevent structure. */
689 EV_SET(&event, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE,
691 /* Attach event to the kqueue. */
692 ret = kevent(kq, &event, 1, NULL, 0, NULL);
694 err(EXIT_FAILURE, "kevent register");
695 if (event.flags & EV_ERROR)
696 errx(EXIT_FAILURE, "Event error: %s", strerror(event.data));
699 /* Sleep until something happens. */
700 ret = kevent(kq, NULL, 0, &tevent, 1, NULL);
702 err(EXIT_FAILURE, "kevent wait");
703 } else if (ret > 0) {
704 printf("Something was written in '%s'\en", argv[1]);
712 system call fails if:
715 The kernel failed to allocate enough memory for the kernel queue.
722 for the current user would be exceeded.
724 The per-process descriptor table is full.
726 The system file table is full.
731 system call fails if:
734 The process does not have permission to register a filter.
736 There was an error reading or writing the
740 The specified descriptor is invalid.
742 A signal was delivered before the timeout expired and before any
743 events were placed on the kqueue for return.
745 A cancellation request was delivered to the thread, but not yet handled.
747 The specified time limit or filter is invalid.
749 The event could not be found to be modified or deleted.
751 No memory was available to register the event
752 or, in the special case of a timer, the maximum number of
753 timers has been exceeded.
754 This maximum is configurable via the
755 .Va kern.kq_calloutmax
758 The specified process to attach to does not exist.
765 error, all changes in the
777 .Xr pthread_setcancelstate 3 ,
781 .%T "Kqueue: A Generic and Scalable Event Notification Facility"
782 .%I USENIX Association
783 .%B Proceedings of the FREENIX Track: 2001 USENIX Annual Technical Conference
785 .\".http://www.usenix.org/event/usenix01/freenix01/full_papers/lemon/lemon.pdf
792 system calls first appeared in
797 system and this manual page were written by
798 .An Jonathan Lemon Aq Mt jlemon@FreeBSD.org .
802 value is limited to 24 hours; longer timeouts will be silently
803 reinterpreted as 24 hours.
805 In versions older than
808 failed to parse without including