xref: /freebsd-13.1/lib/libc/sys/kqueue.2 (revision 108e3076)
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.\" $FreeBSD$
26.\"
27.Dd May 2, 2016
28.Dt KQUEUE 2
29.Os
30.Sh NAME
31.Nm kqueue ,
32.Nm kevent
33.Nd kernel event notification mechanism
34.Sh LIBRARY
35.Lb libc
36.Sh SYNOPSIS
37.In sys/types.h
38.In sys/event.h
39.In sys/time.h
40.Ft int
41.Fn kqueue "void"
42.Ft int
43.Fn kevent "int kq" "const struct kevent *changelist" "int nchanges" "struct kevent *eventlist" "int nevents" "const struct timespec *timeout"
44.Fn EV_SET "kev" ident filter flags fflags data udata
45.Sh DESCRIPTION
46The
47.Fn kqueue
48system call
49provides a generic method of notifying the user when an event
50happens or a condition holds, based on the results of small
51pieces of kernel code termed filters.
52A kevent is identified by the (ident, filter) pair; there may only
53be one unique kevent per kqueue.
54.Pp
55The filter is executed upon the initial registration of a kevent
56in order to detect whether a preexisting condition is present, and is also
57executed whenever an event is passed to the filter for evaluation.
58If the filter determines that the condition should be reported,
59then the kevent is placed on the kqueue for the user to retrieve.
60.Pp
61The filter is also run when the user attempts to retrieve the kevent
62from the kqueue.
63If the filter indicates that the condition that triggered
64the event no longer holds, the kevent is removed from the kqueue and
65is not returned.
66.Pp
67Multiple events which trigger the filter do not result in multiple
68kevents being placed on the kqueue; instead, the filter will aggregate
69the events into a single struct kevent.
70Calling
71.Fn close
72on a file descriptor will remove any kevents that reference the descriptor.
73.Pp
74The
75.Fn kqueue
76system call
77creates a new kernel event queue and returns a descriptor.
78The queue is not inherited by a child created with
79.Xr fork 2 .
80However, if
81.Xr rfork 2
82is called without the
83.Dv RFFDG
84flag, then the descriptor table is shared,
85which will allow sharing of the kqueue between two processes.
86.Pp
87The
88.Fn kevent
89system call
90is used to register events with the queue, and return any pending
91events to the user.
92The
93.Fa changelist
94argument
95is a pointer to an array of
96.Va kevent
97structures, as defined in
98.In sys/event.h .
99All changes contained in the
100.Fa changelist
101are applied before any pending events are read from the queue.
102The
103.Fa nchanges
104argument
105gives the size of
106.Fa changelist .
107The
108.Fa eventlist
109argument
110is a pointer to an array of kevent structures.
111The
112.Fa nevents
113argument
114determines the size of
115.Fa eventlist .
116When
117.Fa nevents
118is zero,
119.Fn kevent
120will return immediately even if there is a
121.Fa timeout
122specified unlike
123.Xr select 2 .
124If
125.Fa timeout
126is a non-NULL pointer, it specifies a maximum interval to wait
127for an event, which will be interpreted as a struct timespec.
128If
129.Fa timeout
130is a NULL pointer,
131.Fn kevent
132waits indefinitely.
133To effect a poll, the
134.Fa timeout
135argument should be non-NULL, pointing to a zero-valued
136.Va timespec
137structure.
138The same array may be used for the
139.Fa changelist
140and
141.Fa eventlist .
142.Pp
143The
144.Fn EV_SET
145macro is provided for ease of initializing a
146kevent structure.
147.Pp
148The
149.Va kevent
150structure is defined as:
151.Bd -literal
152struct kevent {
153	uintptr_t ident;	/* identifier for this event */
154	short	  filter;	/* filter for event */
155	u_short	  flags;	/* action flags for kqueue */
156	u_int	  fflags;	/* filter flag value */
157	intptr_t  data;		/* filter data value */
158	void	  *udata;	/* opaque user data identifier */
159};
160.Ed
161.Pp
162The fields of
163.Fa struct kevent
164are:
165.Bl -tag -width "Fa filter"
166.It Fa ident
167Value used to identify this event.
168The exact interpretation is determined by the attached filter,
169but often is a file descriptor.
170.It Fa filter
171Identifies the kernel filter used to process this event.
172The pre-defined
173system filters are described below.
174.It Fa flags
175Actions to perform on the event.
176.It Fa fflags
177Filter-specific flags.
178.It Fa data
179Filter-specific data value.
180.It Fa udata
181Opaque user-defined value passed through the kernel unchanged.
182.El
183.Pp
184The
185.Va flags
186field can contain the following values:
187.Bl -tag -width EV_DISPATCH
188.It Dv EV_ADD
189Adds the event to the kqueue.
190Re-adding an existing event
191will modify the parameters of the original event, and not result
192in a duplicate entry.
193Adding an event automatically enables it,
194unless overridden by the EV_DISABLE flag.
195.It Dv EV_ENABLE
196Permit
197.Fn kevent
198to return the event if it is triggered.
199.It Dv EV_DISABLE
200Disable the event so
201.Fn kevent
202will not return it.
203The filter itself is not disabled.
204.It Dv EV_DISPATCH
205Disable the event source immediately after delivery of an event.
206See
207.Dv EV_DISABLE
208above.
209.It Dv EV_DELETE
210Removes the event from the kqueue.
211Events which are attached to
212file descriptors are automatically deleted on the last close of
213the descriptor.
214.It Dv EV_RECEIPT
215This flag is useful for making bulk changes to a kqueue without draining
216any pending events.
217When passed as input, it forces
218.Dv EV_ERROR
219to always be returned.
220When a filter is successfully added the
221.Va data
222field will be zero.
223.It Dv EV_ONESHOT
224Causes the event to return only the first occurrence of the filter
225being triggered.
226After the user retrieves the event from the kqueue,
227it is deleted.
228.It Dv EV_CLEAR
229After the event is retrieved by the user, its state is reset.
230This is useful for filters which report state transitions
231instead of the current state.
232Note that some filters may automatically
233set this flag internally.
234.It Dv EV_EOF
235Filters may set this flag to indicate filter-specific EOF condition.
236.It Dv EV_ERROR
237See
238.Sx RETURN VALUES
239below.
240.El
241.Pp
242The predefined system filters are listed below.
243Arguments may be passed to and from the filter via the
244.Va fflags
245and
246.Va data
247fields in the kevent structure.
248.Bl -tag -width "Dv EVFILT_PROCDESC"
249.It Dv EVFILT_READ
250Takes a descriptor as the identifier, and returns whenever
251there is data available to read.
252The behavior of the filter is slightly different depending
253on the descriptor type.
254.Bl -tag -width 2n
255.It Sockets
256Sockets which have previously been passed to
257.Fn listen
258return when there is an incoming connection pending.
259.Va data
260contains the size of the listen backlog.
261.Pp
262Other socket descriptors return when there is data to be read,
263subject to the
264.Dv SO_RCVLOWAT
265value of the socket buffer.
266This may be overridden with a per-filter low water mark at the
267time the filter is added by setting the
268.Dv NOTE_LOWAT
269flag in
270.Va fflags ,
271and specifying the new low water mark in
272.Va data .
273On return,
274.Va data
275contains the number of bytes of protocol data available to read.
276.Pp
277If the read direction of the socket has shutdown, then the filter
278also sets
279.Dv EV_EOF
280in
281.Va flags ,
282and returns the socket error (if any) in
283.Va fflags .
284It is possible for EOF to be returned (indicating the connection is gone)
285while there is still data pending in the socket buffer.
286.It Vnodes
287Returns when the file pointer is not at the end of file.
288.Va data
289contains the offset from current position to end of file,
290and may be negative.
291.Pp
292This behavior is different from
293.Xr poll 2 ,
294where read events are triggered for regular files unconditionally.
295This event can be triggered unconditionally by setting the
296.Dv NOTE_FILE_POLL
297flag in
298.Va fflags .
299.It "Fifos, Pipes"
300Returns when the there is data to read;
301.Va data
302contains the number of bytes available.
303.Pp
304When the last writer disconnects, the filter will set
305.Dv EV_EOF
306in
307.Va flags .
308This may be cleared by passing in
309.Dv EV_CLEAR ,
310at which point the
311filter will resume waiting for data to become available before
312returning.
313.It "BPF devices"
314Returns when the BPF buffer is full, the BPF timeout has expired, or
315when the BPF has
316.Dq immediate mode
317enabled and there is any data to read;
318.Va data
319contains the number of bytes available.
320.El
321.It Dv EVFILT_WRITE
322Takes a descriptor as the identifier, and returns whenever
323it is possible to write to the descriptor.
324For sockets, pipes
325and fifos,
326.Va data
327will contain the amount of space remaining in the write buffer.
328The filter will set EV_EOF when the reader disconnects, and for
329the fifo case, this may be cleared by use of
330.Dv EV_CLEAR .
331Note that this filter is not supported for vnodes or BPF devices.
332.Pp
333For sockets, the low water mark and socket error handling is
334identical to the
335.Dv EVFILT_READ
336case.
337.It Dv EVFILT_AIO
338The sigevent portion of the AIO request is filled in, with
339.Va sigev_notify_kqueue
340containing the descriptor of the kqueue that the event should
341be attached to,
342.Va sigev_notify_kevent_flags
343containing the kevent flags which should be
344.Dv EV_ONESHOT ,
345.Dv EV_CLEAR
346or
347.Dv EV_DISPATCH ,
348.Va sigev_value
349containing the udata value, and
350.Va sigev_notify
351set to
352.Dv SIGEV_KEVENT .
353When the
354.Fn aio_*
355system call is made, the event will be registered
356with the specified kqueue, and the
357.Va ident
358argument set to the
359.Fa struct aiocb
360returned by the
361.Fn aio_*
362system call.
363The filter returns under the same conditions as
364.Fn aio_error .
365.It Dv EVFILT_VNODE
366Takes a file descriptor as the identifier and the events to watch for in
367.Va fflags ,
368and returns when one or more of the requested events occurs on the descriptor.
369The events to monitor are:
370.Bl -tag -width "Dv NOTE_RENAME"
371.It Dv NOTE_DELETE
372The
373.Fn unlink
374system call
375was called on the file referenced by the descriptor.
376.It Dv NOTE_WRITE
377A write occurred on the file referenced by the descriptor.
378.It Dv NOTE_EXTEND
379For regular file, the file referenced by the descriptor was extended.
380.Pp
381For directory, reports that a directory entry was added or removed,
382as the result of rename operation.
383The
384.Dv NOTE_EXTEND
385event is not reported when a name is changed inside the directory.
386.It Dv NOTE_ATTRIB
387The file referenced by the descriptor had its attributes changed.
388.It Dv NOTE_LINK
389The link count on the file changed.
390In particular, the
391.Dv NOTE_LINK
392event is reported if a subdirectory was created or deleted inside
393the directory referenced by the descriptor.
394.It Dv NOTE_RENAME
395The file referenced by the descriptor was renamed.
396.It Dv NOTE_REVOKE
397Access to the file was revoked via
398.Xr revoke 2
399or the underlying file system was unmounted.
400.El
401.Pp
402On return,
403.Va fflags
404contains the events which triggered the filter.
405.It Dv EVFILT_PROC
406Takes the process ID to monitor as the identifier and the events to watch for
407in
408.Va fflags ,
409and returns when the process performs one or more of the requested events.
410If a process can normally see another process, it can attach an event to it.
411The events to monitor are:
412.Bl -tag -width "Dv NOTE_TRACKERR"
413.It Dv NOTE_EXIT
414The process has exited.
415The exit status will be stored in
416.Va data .
417.It Dv NOTE_FORK
418The process has called
419.Fn fork .
420.It Dv NOTE_EXEC
421The process has executed a new process via
422.Xr execve 2
423or a similar call.
424.It Dv NOTE_TRACK
425Follow a process across
426.Fn fork
427calls.
428The parent process registers a new kevent to monitor the child process
429using the same
430.Va fflags
431as the original event.
432The child process will signal an event with
433.Dv NOTE_CHILD
434set in
435.Va fflags
436and the parent PID in
437.Va data .
438.Pp
439If the parent process fails to register a new kevent
440.Pq usually due to resource limitations ,
441it will signal an event with
442.Dv NOTE_TRACKERR
443set in
444.Va fflags ,
445and the child process will not signal a
446.Dv NOTE_CHILD
447event.
448.El
449.Pp
450On return,
451.Va fflags
452contains the events which triggered the filter.
453.It Dv EVFILT_PROCDESC
454Takes the process descriptor created by
455.Xr pdfork 2
456to monitor as the identifier and the events to watch for in
457.Va fflags ,
458and returns when the associated process performs one or more of the
459requested events.
460The events to monitor are:
461.Bl -tag -width "Dv NOTE_EXIT"
462.It Dv NOTE_EXIT
463The process has exited.
464The exit status will be stored in
465.Va data .
466.El
467.Pp
468On return,
469.Va fflags
470contains the events which triggered the filter.
471.It Dv EVFILT_SIGNAL
472Takes the signal number to monitor as the identifier and returns
473when the given signal is delivered to the process.
474This coexists with the
475.Fn signal
476and
477.Fn sigaction
478facilities, and has a lower precedence.
479The filter will record
480all attempts to deliver a signal to a process, even if the signal has
481been marked as
482.Dv SIG_IGN ,
483except for the
484.Dv SIGCHLD
485signal, which, if ignored, won't be recorded by the filter.
486Event notification happens after normal
487signal delivery processing.
488.Va data
489returns the number of times the signal has occurred since the last call to
490.Fn kevent .
491This filter automatically sets the
492.Dv EV_CLEAR
493flag internally.
494.It Dv EVFILT_TIMER
495Establishes an arbitrary timer identified by
496.Va ident .
497When adding a timer,
498.Va data
499specifies the timeout period.
500The timer will be periodic unless
501.Dv EV_ONESHOT
502is specified.
503On return,
504.Va data
505contains the number of times the timeout has expired since the last call to
506.Fn kevent .
507This filter automatically sets the EV_CLEAR flag internally.
508There is a system wide limit on the number of timers
509which is controlled by the
510.Va kern.kq_calloutmax
511sysctl.
512.Bl -tag -width "Dv NOTE_USECONDS"
513.It Dv NOTE_SECONDS
514.Va data
515is in seconds.
516.It Dv NOTE_MSECONDS
517.Va data
518is in milliseconds.
519.It Dv NOTE_USECONDS
520.Va data
521is in microseconds.
522.It Dv NOTE_NSECONDS
523.Va data
524is in nanoseconds.
525.El
526.Pp
527If
528.Va fflags
529is not set, the default is milliseconds. On return,
530.Va fflags
531contains the events which triggered the filter.
532.It Dv EVFILT_USER
533Establishes a user event identified by
534.Va ident
535which is not associated with any kernel mechanism but is triggered by
536user level code.
537The lower 24 bits of the
538.Va fflags
539may be used for user defined flags and manipulated using the following:
540.Bl -tag -width "Dv NOTE_FFLAGSMASK"
541.It Dv NOTE_FFNOP
542Ignore the input
543.Va fflags .
544.It Dv NOTE_FFAND
545Bitwise AND
546.Va fflags .
547.It Dv NOTE_FFOR
548Bitwise OR
549.Va fflags .
550.It Dv NOTE_FFCOPY
551Copy
552.Va fflags .
553.It Dv NOTE_FFCTRLMASK
554Control mask for
555.Va fflags .
556.It Dv NOTE_FFLAGSMASK
557User defined flag mask for
558.Va fflags .
559.El
560.Pp
561A user event is triggered for output with the following:
562.Bl -tag -width "Dv NOTE_FFLAGSMASK"
563.It Dv NOTE_TRIGGER
564Cause the event to be triggered.
565.El
566.Pp
567On return,
568.Va fflags
569contains the users defined flags in the lower 24 bits.
570.El
571.Sh CANCELLATION BEHAVIOUR
572If
573.Fa nevents
574is non-zero, i.e. the function is potentially blocking, the call
575is a cancellation point.
576Otherwise, i.e. if
577.Fa nevents
578is zero, the call is not cancellable.
579Cancellation can only occur before any changes are made to the kqueue,
580or when the call was blocked and no changes to the queue were requested.
581.Sh RETURN VALUES
582The
583.Fn kqueue
584system call
585creates a new kernel event queue and returns a file descriptor.
586If there was an error creating the kernel event queue, a value of -1 is
587returned and errno set.
588.Pp
589The
590.Fn kevent
591system call
592returns the number of events placed in the
593.Fa eventlist ,
594up to the value given by
595.Fa nevents .
596If an error occurs while processing an element of the
597.Fa changelist
598and there is enough room in the
599.Fa eventlist ,
600then the event will be placed in the
601.Fa eventlist
602with
603.Dv EV_ERROR
604set in
605.Va flags
606and the system error in
607.Va data .
608Otherwise,
609.Dv -1
610will be returned, and
611.Dv errno
612will be set to indicate the error condition.
613If the time limit expires, then
614.Fn kevent
615returns 0.
616.Sh EXAMPLES
617.Bd -literal -compact
618#include <sys/types.h>
619#include <sys/event.h>
620#include <sys/time.h>
621#include <err.h>
622#include <fcntl.h>
623#include <stdio.h>
624#include <stdlib.h>
625#include <string.h>
626#include <unistd.h>
627
628int
629main(int argc, char **argv)
630{
631    struct kevent event;    /* Event we want to monitor */
632    struct kevent tevent;   /* Event triggered */
633    int kq, fd, ret;
634
635    if (argc != 2)
636	err(EXIT_FAILURE, "Usage: %s path\en", argv[0]);
637    fd = open(argv[1], O_RDONLY);
638    if (fd == -1)
639	err(EXIT_FAILURE, "Failed to open '%s'", argv[1]);
640
641    /* Create kqueue. */
642    kq = kqueue();
643    if (kq == -1)
644	err(EXIT_FAILURE, "kqueue() failed");
645
646    /* Initialize kevent structure. */
647    EV_SET(&event, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE,
648	0, NULL);
649    /* Attach event to the kqueue. */
650    ret = kevent(kq, &event, 1, NULL, 0, NULL);
651    if (ret == -1)
652	err(EXIT_FAILURE, "kevent register");
653    if (event.flags & EV_ERROR)
654	errx(EXIT_FAILURE, "Event error: %s", strerror(event.data));
655
656    for (;;) {
657	/* Sleep until something happens. */
658	ret = kevent(kq, NULL, 0, &tevent, 1, NULL);
659	if (ret == -1) {
660	    err(EXIT_FAILURE, "kevent wait");
661	} else if (ret > 0) {
662	    printf("Something was written in '%s'\en", argv[1]);
663	}
664    }
665}
666.Ed
667.Sh ERRORS
668The
669.Fn kqueue
670system call fails if:
671.Bl -tag -width Er
672.It Bq Er ENOMEM
673The kernel failed to allocate enough memory for the kernel queue.
674.It Bq Er ENOMEM
675The
676.Dv RLIMIT_KQUEUES
677rlimit
678(see
679.Xr getrlimit 2 )
680for the current user would be exceeded.
681.It Bq Er EMFILE
682The per-process descriptor table is full.
683.It Bq Er ENFILE
684The system file table is full.
685.El
686.Pp
687The
688.Fn kevent
689system call fails if:
690.Bl -tag -width Er
691.It Bq Er EACCES
692The process does not have permission to register a filter.
693.It Bq Er EFAULT
694There was an error reading or writing the
695.Va kevent
696structure.
697.It Bq Er EBADF
698The specified descriptor is invalid.
699.It Bq Er EINTR
700A signal was delivered before the timeout expired and before any
701events were placed on the kqueue for return.
702.It Bq Er EINTR
703A cancellation request was delivered to the thread, but not yet handled.
704.It Bq Er EINVAL
705The specified time limit or filter is invalid.
706.It Bq Er ENOENT
707The event could not be found to be modified or deleted.
708.It Bq Er ENOMEM
709No memory was available to register the event
710or, in the special case of a timer, the maximum number of
711timers has been exceeded.
712This maximum is configurable via the
713.Va kern.kq_calloutmax
714sysctl.
715.It Bq Er ESRCH
716The specified process to attach to does not exist.
717.El
718.Pp
719When
720.Fn kevent
721call fails with
722.Er EINTR
723error, all changes in the
724.Fa changelist
725have been applied.
726.Sh SEE ALSO
727.Xr aio_error 2 ,
728.Xr aio_read 2 ,
729.Xr aio_return 2 ,
730.Xr poll 2 ,
731.Xr read 2 ,
732.Xr select 2 ,
733.Xr sigaction 2 ,
734.Xr write 2 ,
735.Xr pthread_setcancelstate 3 ,
736.Xr signal 3
737.Sh HISTORY
738The
739.Fn kqueue
740and
741.Fn kevent
742system calls first appeared in
743.Fx 4.1 .
744.Sh AUTHORS
745The
746.Fn kqueue
747system and this manual page were written by
748.An Jonathan Lemon Aq Mt [email protected] .
749.Sh BUGS
750The
751.Fa timeout
752value is limited to 24 hours; longer timeouts will be silently
753reinterpreted as 24 hours.
754