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