xref: /freebsd/lib/libsys/kqueue.2 (revision 4cd67a0eea4eba63cf50a45a4665d8700df8d188)
1.\" Copyright (c) 2000 Jonathan Lemon
2.\" All rights reserved.
3.\"
4.\" Redistribution and use in source and binary forms, with or without
5.\" modification, are permitted provided that the following conditions
6.\" are met:
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.
12.\"
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
23.\" SUCH DAMAGE.
24.\"
25.Dd January 24, 2026
26.Dt KQUEUE 2
27.Os
28.Sh NAME
29.Nm kqueue ,
30.Nm kevent
31.Nd kernel event notification mechanism
32.Sh LIBRARY
33.Lb libc
34.Sh SYNOPSIS
35.In sys/event.h
36.Ft int
37.Fn kqueue "void"
38.Ft int
39.Fn kqueuex "u_int flags"
40.Ft int
41.Fn kqueue1 "int flags"
42.Ft int
43.Fo kevent
44.Fa "int kq"
45.Fa "const struct kevent *changelist"
46.Fa "int nchanges"
47.Fa "struct kevent *eventlist"
48.Fa "int nevents"
49.Fa "const struct timespec *timeout"
50.Fc
51.Fn EV_SET "kev" ident filter flags fflags data udata
52.Sh DESCRIPTION
53The
54.Fn kqueue
55system call
56provides a generic method of notifying the user when an event
57happens or a condition holds, based on the results of small
58pieces of kernel code termed filters.
59A kevent is identified by the (ident, filter) pair; there may only
60be one unique kevent per kqueue.
61.Pp
62The filter is executed upon the initial registration of a kevent
63in order to detect whether a preexisting condition is present, and is also
64executed whenever an event is passed to the filter for evaluation.
65If the filter determines that the condition should be reported,
66then the kevent is placed on the kqueue for the user to retrieve.
67.Pp
68The filter is also run when the user attempts to retrieve the kevent
69from the kqueue.
70If the filter indicates that the condition that triggered
71the event no longer holds, the kevent is removed from the kqueue and
72is not returned.
73.Pp
74Multiple events which trigger the filter do not result in multiple
75kevents being placed on the kqueue; instead, the filter will aggregate
76the events into a single struct kevent.
77Calling
78.Fn close
79on a file descriptor will remove any kevents that reference the descriptor.
80.Pp
81The
82.Fn kqueue
83system call
84creates a new kernel event queue and returns a descriptor.
85The queue is not inherited by a child created with
86.Xr fork 2 .
87However, if
88.Xr rfork 2
89is called without the
90.Dv RFFDG
91flag, then the descriptor table is shared,
92which will allow sharing of the kqueue between two processes.
93.Pp
94The
95.Fn kqueuex
96system call also creates a new kernel event queue, and additionally takes
97a
98.Fa flags
99argument, which is a bitwise-inclusive OR of the following flags:
100.Bl -tag -width "KQUEUE_CPONFORK"
101.It Dv KQUEUE_CLOEXEC
102The returned file descriptor is automatically closed on
103.Xr execve 2
104.It Dv KQUEUE_CPONFORK
105When this flag is set, the created kqueue is copied into
106the child process on
107.Xr fork 2
108calls.
109The kqueue descriptor index of the new kqueue will be inherited by the child,
110that is, the numeric value of the descriptor will remain the same.
111.Pp
112Copying is deep, that is, each registered event in the original kqueue is
113copied (and not shared) into the new kqueue.
114This is contrary to how other descriptor types are handled upon
115.Xr fork 2 ,
116where the copied file descriptor references the same file object
117as the source descriptor (shallow copy).
118.Pp
119By default, in other words, when the flag is not set, kqueues from
120the parent are not copied on fork to the child process.
121The corresponding file descriptor indeces are unused in the child.
122.Pp
123Registered events that reference file descriptors which are not
124duplicated on fork, are not copied into the new kqueue.
125For instance, if the event references a file descriptor opened with the
126.Dv O_CLOEXEC
127flag set, it is not copied.
128Similarly, if event references a kqueue opened without the
129.Dv KQUEUE_CPONFORK
130flag, the event is not copied.
131.El
132.Pp
133The
134.Fn kqueue
135system call is equivalent to calling
136.Fn kqueuex
137with
138.Fa flags
139set to 0.
140.Pp
141The
142.Fn kqueue1
143function exists for compatibility with
144.Nx .
145The
146.Fa flags
147argument accepts zero or more of the following values:
148.Bl -tag -width O_CLOEXEC
149.It Dv O_CLOEXEC
150The returned file descriptor is automatically closed on
151.Xr execve 2
152.El
153.Pp
154The
155.Fn kevent
156system call
157is used to register events with the queue, and return any pending
158events to the user.
159The
160.Fa changelist
161argument
162is a pointer to an array of
163.Va kevent
164structures, as defined in
165.In sys/event.h .
166All changes contained in the
167.Fa changelist
168are applied before any pending events are read from the queue.
169The
170.Fa nchanges
171argument
172gives the size of
173.Fa changelist .
174The
175.Fa eventlist
176argument
177is a pointer to an array of kevent structures.
178The
179.Fa nevents
180argument
181determines the size of
182.Fa eventlist .
183When
184.Fa nevents
185is zero,
186.Fn kevent
187will return immediately even if there is a
188.Fa timeout
189specified unlike
190.Xr select 2 .
191If
192.Fa timeout
193is a non-NULL pointer, it specifies a maximum interval to wait
194for an event, which will be interpreted as a struct timespec.
195If
196.Fa timeout
197is a NULL pointer,
198.Fn kevent
199waits indefinitely.
200To effect a poll, the
201.Fa timeout
202argument should be non-NULL, pointing to a zero-valued
203.Va timespec
204structure.
205The same array may be used for the
206.Fa changelist
207and
208.Fa eventlist .
209.Pp
210The
211.Fn EV_SET
212macro is provided for ease of initializing a
213kevent structure.
214.Pp
215The
216.Va kevent
217structure is defined as:
218.Bd -literal
219struct kevent {
220	uintptr_t  ident;	/* identifier for this event */
221	short	  filter;	/* filter for event */
222	u_short	  flags;	/* action flags for kqueue */
223	u_int	  fflags;	/* filter flag value */
224	int64_t   data;		/* filter data value */
225	void	  *udata;	/* opaque user data identifier */
226	uint64_t  ext[4];	/* extensions */
227};
228.Ed
229.Pp
230The fields of
231.Fa struct kevent
232are:
233.Bl -tag -width "Fa filter"
234.It Fa ident
235Value used to identify this event.
236The exact interpretation is determined by the attached filter,
237but often is a file descriptor.
238.It Fa filter
239Identifies the kernel filter used to process this event.
240The pre-defined
241system filters are described below.
242.It Fa flags
243Actions to perform on the event.
244.It Fa fflags
245Filter-specific flags.
246.It Fa data
247Filter-specific data value.
248.It Fa udata
249Opaque user-defined value passed through the kernel unchanged.
250.It Fa ext
251Extended data passed to and from kernel.
252The meaning of the
253.Fa ext[0]
254and
255.Fa ext[1]
256members is defined by the filter.
257If a filter does not use them,
258these members are passed through the kernel unchanged.
259The
260.Fa ext[2]
261and
262.Fa ext[3]
263members are always passed through the kernel unchanged,
264providing additional user-defined values.
265.El
266.Pp
267The
268.Va flags
269field can contain the following values:
270.Bl -tag -width EV_KEEPUDATA
271.It Dv EV_ADD
272Adds the event to the kqueue.
273Re-adding an existing event
274will modify the parameters of the original event, and not result
275in a duplicate entry.
276Adding an event automatically enables it,
277unless overridden by the EV_DISABLE flag.
278.It Dv EV_ENABLE
279Permit
280.Fn kevent
281to return the event if it is triggered.
282.It Dv EV_DISABLE
283Disable the event so
284.Fn kevent
285will not return it.
286The filter itself is not disabled.
287.It Dv EV_DISPATCH
288Disable the event source immediately after delivery of an event.
289See
290.Dv EV_DISABLE
291above.
292.It Dv EV_DELETE
293Removes the event from the kqueue.
294Events which are attached to
295file descriptors are automatically deleted on the last close of
296the descriptor.
297.It Dv EV_RECEIPT
298This flag is useful for making bulk changes to a kqueue without draining
299any pending events.
300When passed as input, it forces
301.Dv EV_ERROR
302to always be returned.
303When a filter is successfully added the
304.Va data
305field will be zero.
306Note that if this flag is encountered and there is no remaining space in
307.Fa eventlist
308to hold the
309.Dv EV_ERROR
310event, then subsequent changes will not get processed.
311.It Dv EV_ONESHOT
312Return only the first occurrence of the filter
313being triggered.
314After the user retrieves the event from the kqueue,
315it is deleted.
316.It Dv EV_CLEAR
317Reset the state of the event after it is retrieved by the user.
318This is useful for filters which report state transitions
319instead of the current state.
320Note that some filters may automatically
321set this flag internally.
322.It Dv EV_EOF
323Filters may set this flag to indicate filter-specific EOF condition.
324.It Dv EV_ERROR
325See
326.Sx RETURN VALUES
327below.
328.It Dv EV_KEEPUDATA
329Preserve the
330.Fa udata
331associated with an existing event.
332This allows other aspects of the event to be modified without requiring the
333caller to know the
334.Fa udata
335value previously registered with the event.
336This is especially useful with
337.Dv NOTE_TRIGGER
338or
339.Dv EV_ENABLE .
340This flag may not be used with
341.Dv EV_ADD .
342.El
343.Pp
344The predefined system filters are listed below.
345Arguments may be passed to and from the filter via the
346.Va fflags
347and
348.Va data
349fields in the kevent structure.
350.Bl -tag -width "Dv EVFILT_PROCDESC"
351.It Dv EVFILT_READ
352Takes a descriptor as the identifier, and returns whenever
353there is data available to read.
354The behavior of the filter is slightly different depending
355on the descriptor type.
356.Bl -tag -width 2n
357.It Sockets
358Sockets which have previously been passed to
359.Xr listen 2
360return when there is an incoming connection pending.
361.Va data
362contains the size of the listen backlog.
363.Pp
364Other socket descriptors return when there is data to be read,
365subject to the
366.Dv SO_RCVLOWAT
367value of the socket buffer.
368This may be overridden with a per-filter low water mark at the
369time the filter is added by setting the
370.Dv NOTE_LOWAT
371flag in
372.Va fflags ,
373and specifying the new low water mark in
374.Va data .
375On return,
376.Va data
377contains the number of bytes of protocol data available to read.
378.Pp
379If the read direction of the socket has shutdown, then the filter
380also sets
381.Dv EV_EOF
382in
383.Va flags ,
384and returns the socket error (if any) in
385.Va fflags .
386It is possible for EOF to be returned (indicating the connection is gone)
387while there is still data pending in the socket buffer.
388.It Vnodes
389Returns when the file pointer is not at the end of file.
390.Va data
391contains the offset from current position to end of file,
392and may be negative.
393.Pp
394This behavior is different from
395.Xr poll 2 ,
396where read events are triggered for regular files unconditionally.
397This event can be triggered unconditionally by setting the
398.Dv NOTE_FILE_POLL
399flag in
400.Va fflags .
401.It "Fifos, Pipes"
402Returns when the there is data to read;
403.Va data
404contains the number of bytes available.
405.Pp
406When the last writer disconnects, the filter will set
407.Dv EV_EOF
408in
409.Va flags .
410This will be cleared by the filter when a new writer connects,
411at which point the
412filter will resume waiting for data to become available before
413returning.
414.It "BPF devices"
415Returns when the BPF buffer is full, the BPF timeout has expired, or
416when the BPF has
417.Dq immediate mode
418enabled and there is any data to read;
419.Va data
420contains the number of bytes available.
421.It Eventfds
422Returns when the counter is greater than 0;
423.Va data
424contains the counter value, which must be cast to
425.Vt uint64_t .
426.It Kqueues
427Returns when pending events are present on the queue;
428.Va data
429contains the number of events available.
430.El
431.It Dv EVFILT_WRITE
432Takes a descriptor as the identifier, and returns whenever
433it is possible to write to the descriptor.
434For sockets, pipes
435and fifos,
436.Va data
437will contain the amount of space remaining in the write buffer.
438The filter will set
439.Dv EV_EOF
440when the reader disconnects, and for the fifo case, this will be cleared
441when a new reader connects.
442Note that this filter is not supported for vnodes.
443.Pp
444For sockets, the low water mark and socket error handling is
445identical to the
446.Dv EVFILT_READ
447case.
448.Pp
449For eventfds,
450.Va data
451will contain the maximum value that can be added to the counter
452without blocking.
453.Pp
454For BPF devices, when the descriptor is attached to an interface the filter
455always indicates that it is possible to write and
456.Va data
457will contain the MTU size of the underlying interface.
458.It Dv EVFILT_EMPTY
459Takes a descriptor as the identifier, and returns whenever
460there is no remaining data in the write buffer.
461.It Dv EVFILT_AIO
462Events for this filter are not registered with
463.Fn kevent
464directly but are registered via the
465.Va aio_sigevent
466member of an asynchronous I/O request when it is scheduled via an
467asynchronous I/O system call such as
468.Fn aio_read .
469The filter returns under the same conditions as
470.Fn aio_error .
471For more details on this filter see
472.Xr sigevent 3 and
473.Xr aio 4 .
474.It Dv EVFILT_VNODE
475Takes a file descriptor as the identifier and the events to watch for in
476.Va fflags ,
477and returns when one or more of the requested events occurs on the descriptor.
478The events to monitor are:
479.Bl -tag -width "Dv NOTE_CLOSE_WRITE"
480.It Dv NOTE_ATTRIB
481The file referenced by the descriptor had its attributes changed.
482.It Dv NOTE_CLOSE
483A file descriptor referencing the monitored file, was closed.
484The closed file descriptor did not have write access.
485.It Dv NOTE_CLOSE_WRITE
486A file descriptor referencing the monitored file, was closed.
487The closed file descriptor had write access.
488.Pp
489This note, as well as
490.Dv NOTE_CLOSE ,
491are not activated when files are closed forcibly by
492.Xr unmount 2 or
493.Xr revoke 2 .
494Instead,
495.Dv NOTE_REVOKE
496is sent for such events.
497.It Dv NOTE_DELETE
498The
499.Fn unlink
500system call was called on the file referenced by the descriptor.
501.It Dv NOTE_EXTEND
502For regular file, the file referenced by the descriptor was extended.
503.Pp
504For directory, reports that a directory entry was added or removed,
505as the result of rename operation.
506The
507.Dv NOTE_EXTEND
508event is not reported when a name is changed inside the directory.
509.It Dv NOTE_LINK
510The link count on the file changed.
511In particular, the
512.Dv NOTE_LINK
513event is reported if a subdirectory was created or deleted inside
514the directory referenced by the descriptor.
515.It Dv NOTE_OPEN
516The file referenced by the descriptor was opened.
517.It Dv NOTE_READ
518A read occurred on the file referenced by the descriptor.
519.It Dv NOTE_RENAME
520The file referenced by the descriptor was renamed.
521.It Dv NOTE_REVOKE
522Access to the file was revoked via
523.Xr revoke 2
524or the underlying file system was unmounted.
525.It Dv NOTE_WRITE
526A write occurred on the file referenced by the descriptor.
527.El
528.Pp
529On return,
530.Va fflags
531contains the events which triggered the filter.
532.It Dv EVFILT_PROC
533Takes the process ID to monitor as the identifier and the events to watch for
534in
535.Va fflags ,
536and returns when the process performs one or more of the requested events.
537If a process can normally see another process, it can attach an event to it.
538The events to monitor are:
539.Bl -tag -width "Dv NOTE_TRACKERR"
540.It Dv NOTE_EXIT
541The process has exited.
542The exit status will be stored in
543.Va data
544in the same format as the status returned by
545.Xr wait 2 .
546.It Dv NOTE_FORK
547The process has called
548.Fn fork .
549.It Dv NOTE_EXEC
550The process has executed a new process via
551.Xr execve 2
552or a similar call.
553.It Dv NOTE_TRACK
554Follow a process across
555.Fn fork
556calls.
557The parent process registers a new kevent to monitor the child process
558using the same
559.Va fflags
560as the original event.
561The child process will signal an event with
562.Dv NOTE_CHILD
563set in
564.Va fflags
565and the parent PID in
566.Va data .
567.Pp
568If the parent process fails to register a new kevent
569.Pq usually due to resource limitations ,
570it will signal an event with
571.Dv NOTE_TRACKERR
572set in
573.Va fflags ,
574and the child process will not signal a
575.Dv NOTE_CHILD
576event.
577.El
578.Pp
579On return,
580.Va fflags
581contains the events which triggered the filter.
582.It Dv EVFILT_PROCDESC
583Takes the process descriptor created by
584.Xr pdfork 2
585to monitor as the identifier and the events to watch for in
586.Va fflags ,
587and returns when the associated process performs one or more of the
588requested events.
589The events to monitor are:
590.Bl -tag -width "Dv NOTE_PDSIGCHLD"
591.It Dv NOTE_EXIT
592The process has exited.
593The exit status will be stored in
594.Va data .
595.It Dv NOTE_PDSIGCHLD
596Activates on events that are reported through
597.Xr pdwait 2
598on the process descriptor.
599After the event is reported, the
600.Xr pdwait 2
601can be called to obtain the information about the process
602status change.
603.El
604.Pp
605On return,
606.Va fflags
607contains the events which triggered the filter.
608.It Dv EVFILT_SIGNAL
609Takes the signal number to monitor as the identifier and returns
610when the given signal is delivered to the process.
611This coexists with the
612.Fn signal
613and
614.Fn sigaction
615facilities, and has a lower precedence.
616The filter will record
617all attempts to deliver a signal to a process, even if the signal has
618been marked as
619.Dv SIG_IGN ,
620except for the
621.Dv SIGCHLD
622signal, which, if ignored, will not be recorded by the filter.
623Event notification happens before normal
624signal delivery processing.
625.Va data
626returns the number of times the signal has occurred since the last call to
627.Fn kevent .
628This filter automatically sets the
629.Dv EV_CLEAR
630flag internally.
631.It Dv EVFILT_JAIL
632Takes the jail ID to monitor as the identifier and the events to watch for
633in
634.Va fflags ,
635and returns when the jail performs one or more of the requested events.
636If a process can normally see a jail, it can attach an event to it.
637An identifier of zero will watch the process's own jail.
638The events to monitor are:
639.Bl -tag -width "Dv NOTE_JAIL_ATTACH"
640.It Dv NOTE_JAIL_SET
641The jail has been changed via
642.Xr jail_set 2 .
643.It Dv NOTE_JAIL_ATTACH
644A process has attached to the jail via
645.Xr jail_attach 2
646or a similar call.
647The process ID will be stored in
648.Va data .
649If more than one process has attached since the last call to
650.Fn kevent ,
651.Va data
652will be zero.
653.It Dv NOTE_JAIL_REMOVE
654The jail has been removed.
655.It Dv NOTE_JAIL_CHILD
656A child of the watched jail has been created.
657Its jail ID will be stored in
658.Va data .
659If more than one jail has been created since the last call to
660.Fn kevent ,
661.Va data
662will be zero.
663.El
664.Pp
665On return,
666.Va fflags
667contains the events which triggered the filter.
668It will also contain
669.Dv NOTE_JAIL_MULTI
670if more than one
671.Dv NOTE_JAIL_ATTACH
672or
673.Dv NOTE_JAIL_CHILD
674event has been received since the last call to
675.Fn kevent .
676.It Dv EVFILT_JAILDESC
677Takes a jail descriptor returned by
678.Xr jail_set 2
679or
680.Xr jail_get 2
681as the identifier and the events to watch for in
682.Va fflags ,
683and returns when the jail performs one or more of the requested events.
684The events to monitor and the resulting
685.Va fflags
686are the same as those listed in
687.Dv EVFILT_JAIL ,
688above.
689.It Dv EVFILT_TIMER
690Establishes an arbitrary timer identified by
691.Va ident .
692When adding a timer,
693.Va data
694specifies the moment to fire the timer (for
695.Dv NOTE_ABSTIME )
696or the timeout period.
697The timer will be periodic unless
698.Dv EV_ONESHOT
699or
700.Dv NOTE_ABSTIME
701is specified.
702On return,
703.Va data
704contains the number of times the timeout has expired since the last call to
705.Fn kevent .
706For non-monotonic timers, this filter automatically sets the
707.Dv EV_CLEAR
708flag internally.
709.Pp
710The filter accepts the following flags in the
711.Va fflags
712argument:
713.Bl -tag -width "Dv NOTE_MSECONDS"
714.It Dv NOTE_SECONDS
715.Va data
716is in seconds.
717.It Dv NOTE_MSECONDS
718.Va data
719is in milliseconds.
720.It Dv NOTE_USECONDS
721.Va data
722is in microseconds.
723.It Dv NOTE_NSECONDS
724.Va data
725is in nanoseconds.
726.It Dv NOTE_ABSTIME
727The specified expiration time is absolute.
728.El
729.Pp
730If
731.Va fflags
732is not set, the default is milliseconds.
733On return,
734.Va fflags
735contains the events which triggered the filter.
736.Pp
737Periodic timers with a specified timeout of 0 will be silently adjusted to
738timeout after 1 of the time units specified by the requested precision in
739.Va fflags .
740If an absolute time is specified that has already passed, then it is treated as
741if the current time were specified and the event will fire as soon as possible.
742.Pp
743If an existing timer is re-added, the existing timer will be
744effectively canceled (throwing away any undelivered record of previous
745timer expiration) and re-started using the new parameters contained in
746.Va data
747and
748.Va fflags .
749.Pp
750There is a system wide limit on the number of timers
751which is controlled by the
752.Va kern.kq_calloutmax
753sysctl.
754.It Dv EVFILT_USER
755Establishes a user event identified by
756.Va ident
757which is not associated with any kernel mechanism but is triggered by
758user level code.
759The lower 24 bits of the
760.Va fflags
761may be used for user defined flags and manipulated using the following:
762.Bl -tag -width "Dv NOTE_FFLAGSMASK"
763.It Dv NOTE_FFNOP
764Ignore the input
765.Va fflags .
766.It Dv NOTE_FFAND
767Bitwise AND
768.Va fflags .
769.It Dv NOTE_FFOR
770Bitwise OR
771.Va fflags .
772.It Dv NOTE_FFCOPY
773Copy
774.Va fflags .
775.It Dv NOTE_FFCTRLMASK
776Control mask for
777.Va fflags .
778.It Dv NOTE_FFLAGSMASK
779User defined flag mask for
780.Va fflags .
781.El
782.Pp
783A user event is triggered for output with the following:
784.Bl -tag -width "Dv NOTE_FFLAGSMASK"
785.It Dv NOTE_TRIGGER
786Cause the event to be triggered.
787.El
788.Pp
789On return,
790.Va fflags
791contains the users defined flags in the lower 24 bits.
792.El
793.Sh CANCELLATION BEHAVIOUR
794If
795.Fa nevents
796is non-zero, i.e., the function is potentially blocking, the call
797is a cancellation point.
798Otherwise, i.e., if
799.Fa nevents
800is zero, the call is not cancellable.
801Cancellation can only occur before any changes are made to the kqueue,
802or when the call was blocked and no changes to the queue were requested.
803.Sh RETURN VALUES
804The
805.Fn kqueue
806system call
807creates a new kernel event queue and returns a file descriptor.
808If there was an error creating the kernel event queue, a value of -1 is
809returned and errno set.
810.Pp
811The
812.Fn kevent
813system call
814returns the number of events placed in the
815.Fa eventlist ,
816up to the value given by
817.Fa nevents .
818If an error occurs while processing an element of the
819.Fa changelist
820and there is enough room in the
821.Fa eventlist ,
822then the event will be placed in the
823.Fa eventlist
824with
825.Dv EV_ERROR
826set in
827.Va flags
828and the system error in
829.Va data .
830Otherwise,
831.Dv -1
832will be returned, and
833.Dv errno
834will be set to indicate the error condition.
835If the time limit expires, then
836.Fn kevent
837returns 0.
838.Sh EXAMPLES
839.Bd -literal -compact
840#include <sys/event.h>
841#include <err.h>
842#include <fcntl.h>
843#include <stdio.h>
844#include <stdlib.h>
845#include <string.h>
846
847int
848main(int argc, char **argv)
849{
850    struct kevent event;    /* Event we want to monitor */
851    struct kevent tevent;   /* Event triggered */
852    int kq, fd, ret;
853
854    if (argc != 2)
855	err(EXIT_FAILURE, "Usage: %s path\en", argv[0]);
856    fd = open(argv[1], O_RDONLY);
857    if (fd == -1)
858	err(EXIT_FAILURE, "Failed to open '%s'", argv[1]);
859
860    /* Create kqueue. */
861    kq = kqueue();
862    if (kq == -1)
863	err(EXIT_FAILURE, "kqueue() failed");
864
865    /* Initialize kevent structure. */
866    EV_SET(&event, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE,
867	0, NULL);
868    /* Attach event to the kqueue. */
869    ret = kevent(kq, &event, 1, NULL, 0, NULL);
870    if (ret == -1)
871	err(EXIT_FAILURE, "kevent register");
872
873    for (;;) {
874	/* Sleep until something happens. */
875	ret = kevent(kq, NULL, 0, &tevent, 1, NULL);
876	if (ret == -1) {
877	    err(EXIT_FAILURE, "kevent wait");
878	} else if (ret > 0) {
879	    if (tevent.flags & EV_ERROR)
880		errx(EXIT_FAILURE, "Event error: %s", strerror(event.data));
881	    else
882		printf("Something was written in '%s'\en", argv[1]);
883	}
884    }
885
886    /* kqueues are destroyed upon close() */
887    (void)close(kq);
888    (void)close(fd);
889}
890.Ed
891.Sh ERRORS
892The
893.Fn kqueue
894system call fails if:
895.Bl -tag -width Er
896.It Bq Er ENOMEM
897The kernel failed to allocate enough memory for the kernel queue.
898.It Bq Er ENOMEM
899The
900.Dv RLIMIT_KQUEUES
901rlimit
902(see
903.Xr getrlimit 2 )
904for the current user would be exceeded.
905.It Bq Er EMFILE
906The per-process descriptor table is full.
907.It Bq Er ENFILE
908The system file table is full.
909.El
910.Pp
911The
912.Fn kevent
913system call fails if:
914.Bl -tag -width Er
915.It Bq Er EACCES
916The process does not have permission to register a filter.
917.It Bq Er EFAULT
918There was an error reading or writing the
919.Va kevent
920structure.
921.It Bq Er EBADF
922The specified descriptor is invalid.
923.It Bq Er EINTR
924A signal was delivered before the timeout expired and before any
925events were placed on the kqueue for return.
926.It Bq Er EINTR
927A cancellation request was delivered to the thread, but not yet handled.
928.It Bq Er EINVAL
929The specified time limit or filter is invalid.
930.It Bq Er EINVAL
931The specified length of the event or change lists is negative.
932.It Bq Er ENOENT
933The event could not be found to be modified or deleted.
934.It Bq Er ENOMEM
935No memory was available to register the event
936or, in the special case of a timer, the maximum number of
937timers has been exceeded.
938This maximum is configurable via the
939.Va kern.kq_calloutmax
940sysctl.
941.It Bq Er ESRCH
942The specified process to attach to does not exist.
943.El
944.Pp
945When
946.Fn kevent
947call fails with
948.Er EINTR
949error, all changes in the
950.Fa changelist
951have been applied.
952.Sh SEE ALSO
953.Xr aio_error 2 ,
954.Xr aio_read 2 ,
955.Xr aio_return 2 ,
956.Xr poll 2 ,
957.Xr read 2 ,
958.Xr select 2 ,
959.Xr sigaction 2 ,
960.Xr write 2 ,
961.Xr pthread_setcancelstate 3 ,
962.Xr signal 3
963.Rs
964.%A Jonathan Lemon
965.%T "Kqueue: A Generic and Scalable Event Notification Facility"
966.%I USENIX Association
967.%B Proceedings of the FREENIX Track: 2001 USENIX Annual Technical Conference
968.%D June 25-30, 2001
969.\".http://www.usenix.org/event/usenix01/freenix01/full_papers/lemon/lemon.pdf
970.Re
971.Sh HISTORY
972The
973.Fn kqueue
974and
975.Fn kevent
976system calls first appeared in
977.Fx 4.1 .
978The
979.Fn kqueuex
980system call
981and
982.Fn kqueue1
983function first appeared in
984.Fx 14.0 .
985.Sh AUTHORS
986The
987.Em kqueue
988subsystem and this manual page were written by
989.An Jonathan Lemon Aq Mt jlemon@FreeBSD.org .
990.Sh BUGS
991.Pp
992In versions older than
993.Fx 12.0 ,
994.In sys/event.h
995failed to parse without including
996.In sys/types.h
997manually.
998