1LIBUV(1)                    libuv API documentation                   LIBUV(1)
2
3
4

NAME

6       libuv - libuv documentation
7

OVERVIEW

9       libuv  is a multi-platform support library with a focus on asynchronous
10       I/O. It was primarily developed for use by Node.js, but it's also  used
11       by Luvit, Julia, uvloop, and others.
12
13       NOTE:
14          In  case you find errors in this documentation you can help by send‐
15          ing pull requests!
16

FEATURES

18       • Full-featured event loop backed by epoll, kqueue, IOCP, event ports.
19
20       • Asynchronous TCP and UDP sockets
21
22       • Asynchronous DNS resolution
23
24       • Asynchronous file and file system operations
25
26       • File system events
27
28       • ANSI escape code controlled TTY
29
30       • IPC with socket sharing, using Unix domain  sockets  or  named  pipes
31         (Windows)
32
33       • Child processes
34
35       • Thread pool
36
37       • Signal handling
38
39       • High resolution clock
40
41       • Threading and synchronization primitives
42

DOCUMENTATION

44   Design overview
45       libuv  is  cross-platform  support library which was originally written
46       for Node.js. It's designed around  the  event-driven  asynchronous  I/O
47       model.
48
49       The library provides much more than a simple abstraction over different
50       I/O polling mechanisms: 'handles' and 'streams' provide  a  high  level
51       abstraction for sockets and other entities; cross-platform file I/O and
52       threading functionality is also provided, amongst other things.
53
54       Here is a diagram illustrating the different parts that  compose  libuv
55       and what subsystem they relate to: [image]
56
57   Handles and requests
58       libuv  provides  users with 2 abstractions to work with, in combination
59       with the event loop: handles and requests.
60
61       Handles represent long-lived objects capable of performing certain  op‐
62       erations while active. Some examples:
63
64       • A  prepare  handle gets its callback called once every loop iteration
65         when active.
66
67       • A TCP server handle that gets its connection  callback  called  every
68         time there is a new connection.
69
70       Requests represent (typically) short-lived operations. These operations
71       can be performed over a handle: write requests are used to  write  data
72       on  a  handle;  or standalone: getaddrinfo requests don't need a handle
73       they run directly on the loop.
74
75   The I/O loop
76       The I/O (or event) loop is the central part of  libuv.  It  establishes
77       the content for all I/O operations, and it's meant to be tied to a sin‐
78       gle thread. One can run multiple event loops as long as each runs in  a
79       different  thread. The libuv event loop (or any other API involving the
80       loop or handles, for that  matter)  is  not  thread-safe  except  where
81       stated otherwise.
82
83       The  event  loop  follows the rather usual single threaded asynchronous
84       I/O approach: all (network) I/O is performed  on  non-blocking  sockets
85       which  are polled using the best mechanism available on the given plat‐
86       form: epoll on Linux, kqueue on OSX and  other  BSDs,  event  ports  on
87       SunOS  and  IOCP  on Windows. As part of a loop iteration the loop will
88       block waiting for I/O activity on sockets which have been added to  the
89       poller  and callbacks will be fired indicating socket conditions (read‐
90       able, writable hangup) so handles can read, write or  perform  the  de‐
91       sired I/O operation.
92
93       In  order to better understand how the event loop operates, the follow‐
94       ing diagram illustrates all stages of a loop iteration: [image]
95
96       1.  The loop concept of 'now' is initially set.
97
98       2.  Due timers are run if the loop was run with UV_RUN_DEFAULT. All ac‐
99           tive  timers  scheduled for a time before the loop's concept of now
100           get their callbacks called.
101
102       3.  If the loop is alive  an iteration is started, otherwise  the  loop
103           will  exit  immediately. So, when is a loop considered to be alive?
104           If a loop has active and ref'd handles, active requests or  closing
105           handles it's considered to be alive.
106
107       4.  Pending  callbacks  are  called. All I/O callbacks are called right
108           after polling for I/O, for the most part. There are cases, however,
109           in  which calling such a callback is deferred for the next loop it‐
110           eration. If the previous iteration deferred  any  I/O  callback  it
111           will be run at this point.
112
113       5.  Idle  handle  callbacks  are  called. Despite the unfortunate name,
114           idle handles are run on every loop iteration, if they are active.
115
116       6.  Prepare handle callbacks are  called.  Prepare  handles  get  their
117           callbacks called right before the loop will block for I/O.
118
119       7.  Poll timeout is calculated. Before blocking for I/O the loop calcu‐
120           lates for how long it should block. These are the rules when calcu‐
121           lating the timeout:
122
123              • If  the  loop was run with the UV_RUN_NOWAIT flag, the timeout
124                is 0.
125
126              • If the loop is going to be stopped (uv_stop() was called), the
127                timeout is 0.
128
129              • If there are no active handles or requests, the timeout is 0.
130
131              • If there are any idle handles active, the timeout is 0.
132
133              • If  there are any handles pending to be closed, the timeout is
134                0.
135
136              • If none of the above cases matches, the timeout of the closest
137                timer is taken, or if there are no active timers, infinity.
138
139       8.  The  loop blocks for I/O. At this point the loop will block for I/O
140           for the duration calculated in the previous step. All  I/O  related
141           handles  that were monitoring a given file descriptor for a read or
142           write operation get their callbacks called at this point.
143
144       9.  Check handle callbacks are called. Check handles  get  their  call‐
145           backs  called  right after the loop has blocked for I/O. Check han‐
146           dles are essentially the counterpart of prepare handles.
147
148       10. Close callbacks are called. If  a  handle  was  closed  by  calling
149           uv_close() it will get the close callback called.
150
151       11. The loop concept of 'now' is updated.
152
153       12. Due  timers are run. Note that 'now' is not updated again until the
154           next loop iteration.  So if a timer became due while  other  timers
155           were  being  processed,  it  won't be run until the following event
156           loop iteration.
157
158       13. Iteration  ends.  If  the  loop  was  run  with  UV_RUN_NOWAIT   or
159           UV_RUN_ONCE  modes  the iteration ends and uv_run() will return. If
160           the loop was run with UV_RUN_DEFAULT  it  will  continue  from  the
161           start if it's still alive, otherwise it will also end.
162
163       IMPORTANT:
164          libuv  uses  a  thread pool to make asynchronous file I/O operations
165          possible, but network I/O is always performed in  a  single  thread,
166          each loop's thread.
167
168       NOTE:
169          While  the polling mechanism is different, libuv makes the execution
170          model consistent across Unix systems and Windows.
171
172   File I/O
173       Unlike network I/O, there are no platform-specific file I/O  primitives
174       libuv  could  rely  on, so the current approach is to run blocking file
175       I/O operations in a thread pool.
176
177       For a thorough explanation of the cross-platform  file  I/O  landscape,
178       check out this post.
179
180       libuv  currently uses a global thread pool on which all loops can queue
181       work. 3 types of operations are currently run on this pool:
182
183          • File system operations
184
185          • DNS functions (getaddrinfo and getnameinfo)
186
187          • User specified code via uv_queue_work()
188
189       WARNING:
190          See the Thread pool work scheduling section for  more  details,  but
191          keep in mind the thread pool size is quite limited.
192
193   API documentation
194   Error handling
195       In  libuv  errors  are negative numbered constants. As a rule of thumb,
196       whenever there is a status parameter, or an API  functions  returns  an
197       integer, a negative number will imply an error.
198
199       When  a  function which takes a callback returns an error, the callback
200       will never be called.
201
202       NOTE:
203          Implementation detail: on Unix error codes are the negated errno (or
204          -errno),  while  on  Windows  they are defined by libuv to arbitrary
205          negative numbers.
206
207   Error constants
208       UV_E2BIG
209              argument list too long
210
211       UV_EACCES
212              permission denied
213
214       UV_EADDRINUSE
215              address already in use
216
217       UV_EADDRNOTAVAIL
218              address not available
219
220       UV_EAFNOSUPPORT
221              address family not supported
222
223       UV_EAGAIN
224              resource temporarily unavailable
225
226       UV_EAI_ADDRFAMILY
227              address family not supported
228
229       UV_EAI_AGAIN
230              temporary failure
231
232       UV_EAI_BADFLAGS
233              bad ai_flags value
234
235       UV_EAI_BADHINTS
236              invalid value for hints
237
238       UV_EAI_CANCELED
239              request canceled
240
241       UV_EAI_FAIL
242              permanent failure
243
244       UV_EAI_FAMILY
245              ai_family not supported
246
247       UV_EAI_MEMORY
248              out of memory
249
250       UV_EAI_NODATA
251              no address
252
253       UV_EAI_NONAME
254              unknown node or service
255
256       UV_EAI_OVERFLOW
257              argument buffer overflow
258
259       UV_EAI_PROTOCOL
260              resolved protocol is unknown
261
262       UV_EAI_SERVICE
263              service not available for socket type
264
265       UV_EAI_SOCKTYPE
266              socket type not supported
267
268       UV_EALREADY
269              connection already in progress
270
271       UV_EBADF
272              bad file descriptor
273
274       UV_EBUSY
275              resource busy or locked
276
277       UV_ECANCELED
278              operation canceled
279
280       UV_ECHARSET
281              invalid Unicode character
282
283       UV_ECONNABORTED
284              software caused connection abort
285
286       UV_ECONNREFUSED
287              connection refused
288
289       UV_ECONNRESET
290              connection reset by peer
291
292       UV_EDESTADDRREQ
293              destination address required
294
295       UV_EEXIST
296              file already exists
297
298       UV_EFAULT
299              bad address in system call argument
300
301       UV_EFBIG
302              file too large
303
304       UV_EHOSTUNREACH
305              host is unreachable
306
307       UV_EINTR
308              interrupted system call
309
310       UV_EINVAL
311              invalid argument
312
313       UV_EIO i/o error
314
315       UV_EISCONN
316              socket is already connected
317
318       UV_EISDIR
319              illegal operation on a directory
320
321       UV_ELOOP
322              too many symbolic links encountered
323
324       UV_EMFILE
325              too many open files
326
327       UV_EMSGSIZE
328              message too long
329
330       UV_ENAMETOOLONG
331              name too long
332
333       UV_ENETDOWN
334              network is down
335
336       UV_ENETUNREACH
337              network is unreachable
338
339       UV_ENFILE
340              file table overflow
341
342       UV_ENOBUFS
343              no buffer space available
344
345       UV_ENODEV
346              no such device
347
348       UV_ENOENT
349              no such file or directory
350
351       UV_ENOMEM
352              not enough memory
353
354       UV_ENONET
355              machine is not on the network
356
357       UV_ENOPROTOOPT
358              protocol not available
359
360       UV_ENOSPC
361              no space left on device
362
363       UV_ENOSYS
364              function not implemented
365
366       UV_ENOTCONN
367              socket is not connected
368
369       UV_ENOTDIR
370              not a directory
371
372       UV_ENOTEMPTY
373              directory not empty
374
375       UV_ENOTSOCK
376              socket operation on non-socket
377
378       UV_ENOTSUP
379              operation not supported on socket
380
381       UV_EOVERFLOW
382              value too large for defined data type
383
384       UV_EPERM
385              operation not permitted
386
387       UV_EPIPE
388              broken pipe
389
390       UV_EPROTO
391              protocol error
392
393       UV_EPROTONOSUPPORT
394              protocol not supported
395
396       UV_EPROTOTYPE
397              protocol wrong type for socket
398
399       UV_ERANGE
400              result too large
401
402       UV_EROFS
403              read-only file system
404
405       UV_ESHUTDOWN
406              cannot send after transport endpoint shutdown
407
408       UV_ESPIPE
409              invalid seek
410
411       UV_ESRCH
412              no such process
413
414       UV_ETIMEDOUT
415              connection timed out
416
417       UV_ETXTBSY
418              text file is busy
419
420       UV_EXDEV
421              cross-device link not permitted
422
423       UV_UNKNOWN
424              unknown error
425
426       UV_EOF end of file
427
428       UV_ENXIO
429              no such device or address
430
431       UV_EMLINK
432              too many links
433
434       UV_ENOTTY
435              inappropriate ioctl for device
436
437       UV_EFTYPE
438              inappropriate file type or format
439
440       UV_EILSEQ
441              illegal byte sequence
442
443       UV_ESOCKTNOSUPPORT
444              socket type not supported
445
446       UV_EUNATCH
447              protocol driver not attached
448
449   API
450       UV_ERRNO_MAP(iter_macro)
451              Macro that expands to a series of invocations of iter_macro  for
452              each  of  the  error constants above. iter_macro is invoked with
453              two arguments: the name of the error constant  without  the  UV_
454              prefix, and the error message string literal.
455
456       const char *uv_strerror(int err)
457              Returns the error message for the given error code.  Leaks a few
458              bytes of memory when you call it with an unknown error code.
459
460       char *uv_strerror_r(int err, char *buf, size_t buflen)
461              Returns  the  error  message  for  the  given  error  code.  The
462              zero-terminated  message  is  stored in the user-supplied buffer
463              buf of at most buflen bytes.
464
465              New in version 1.22.0.
466
467
468       const char *uv_err_name(int err)
469              Returns the error name for the given error code.   Leaks  a  few
470              bytes of memory when you call it with an unknown error code.
471
472       char *uv_err_name_r(int err, char *buf, size_t buflen)
473              Returns the error name for the given error code. The zero-termi‐
474              nated name is stored in the user-supplied buffer buf of at  most
475              buflen bytes.
476
477              New in version 1.22.0.
478
479
480       int uv_translate_sys_error(int sys_errno)
481              Returns  the  libuv  error code equivalent to the given platform
482              dependent error code: POSIX error codes on Unix (the ones stored
483              in  errno),  and Win32 error codes on Windows (those returned by
484              GetLastError() or WSAGetLastError()).
485
486              If sys_errno is already a libuv error, it is simply returned.
487
488              Changed in version 1.10.0: function declared public.
489
490
491   Version-checking macros and functions
492       Starting with version  1.0.0  libuv  follows  the  semantic  versioning
493       scheme. This means that new APIs can be introduced throughout the life‐
494       time of a major release. In this section you'll  find  all  macros  and
495       functions  that  will allow you to write or compile code conditionally,
496       in order to work with multiple libuv versions.
497
498   Macros
499       UV_VERSION_MAJOR
500              libuv version's major number.
501
502       UV_VERSION_MINOR
503              libuv version's minor number.
504
505       UV_VERSION_PATCH
506              libuv version's patch number.
507
508       UV_VERSION_IS_RELEASE
509              Set to 1 to indicate a release version of libuv, 0 for a  devel‐
510              opment snapshot.
511
512       UV_VERSION_SUFFIX
513              libuv  version  suffix. Certain development releases such as Re‐
514              lease Candidates might have a suffix such as "rc".
515
516       UV_VERSION_HEX
517              Returns the libuv version packed into a single integer.  8  bits
518              are used for each component, with the patch number stored in the
519              8 least significant bits. E.g. for libuv  1.2.3  this  would  be
520              0x010203.
521
522              New in version 1.7.0.
523
524
525   Functions
526       unsigned int uv_version(void)
527              Returns UV_VERSION_HEX.
528
529       const char *uv_version_string(void)
530              Returns  the  libuv  version number as a string. For non-release
531              versions the version suffix is included.
532
533   uv_loop_t --- Event loop
534       The event loop is the central part of libuv's functionality.  It  takes
535       care  of  polling  for  i/o and scheduling callbacks to be run based on
536       different sources of events.
537
538   Data types
539       type uv_loop_t
540              Loop data type.
541
542       enum uv_run_mode
543              Mode used to run the loop with uv_run().
544
545                 typedef enum {
546                     UV_RUN_DEFAULT = 0,
547                     UV_RUN_ONCE,
548                     UV_RUN_NOWAIT
549                 } uv_run_mode;
550
551       typedef void (*uv_walk_cb)(uv_handle_t *handle, void *arg)
552              Type definition for callback passed to uv_walk().
553
554   Public members
555       void *uv_loop_t.data
556              Space for user-defined arbitrary data. libuv does  not  use  and
557              does not touch this field.
558
559   API
560       int uv_loop_init(uv_loop_t *loop)
561              Initializes the given uv_loop_t structure.
562
563       int uv_loop_configure(uv_loop_t *loop, uv_loop_option option, ...)
564              New in version 1.0.2.
565
566
567              Set  additional loop options.  You should normally call this be‐
568              fore the first call to uv_run() unless mentioned otherwise.
569
570              Returns 0 on success or a UV_E* error code on failure.  Be  pre‐
571              pared  to handle UV_ENOSYS; it means the loop option is not sup‐
572              ported by the platform.
573
574              Supported options:
575
576              • UV_LOOP_BLOCK_SIGNAL: Block a  signal  when  polling  for  new
577                events.   The  second  argument  to uv_loop_configure() is the
578                signal number.
579
580                This operation is currently only implemented for SIGPROF  sig‐
581                nals,  to  suppress  unnecessary wakeups when using a sampling
582                profiler.  Requesting other signals will fail with UV_EINVAL.
583
584              • UV_METRICS_IDLE_TIME: Accumulate the amount of idle  time  the
585                event loop spends in the event provider.
586
587                This option is necessary to use uv_metrics_idle_time().
588
589              Changed  in  version  1.39.0: added the UV_METRICS_IDLE_TIME op‐
590              tion.
591
592
593       int uv_loop_close(uv_loop_t *loop)
594              Releases all internal loop resources. Call  this  function  only
595              when  the  loop  has finished executing and all open handles and
596              requests have been closed, or it  will  return  UV_EBUSY.  After
597              this  function  returns,  the user can free the memory allocated
598              for the loop.
599
600       uv_loop_t *uv_default_loop(void)
601              Returns the initialized default loop. It may return NULL in case
602              of allocation failure.
603
604              This  function is just a convenient way for having a global loop
605              throughout an application, the default loop is in no way differ‐
606              ent  than the ones initialized with uv_loop_init(). As such, the
607              default loop can (and should) be closed with uv_loop_close()  so
608              the resources associated with it are freed.
609
610              WARNING:
611                 This function is not thread safe.
612
613       int uv_run(uv_loop_t *loop, uv_run_mode mode)
614              This  function  runs the event loop. It will act differently de‐
615              pending on the specified mode:
616
617              • UV_RUN_DEFAULT: Runs the event loop until there  are  no  more
618                active and referenced handles or requests. Returns non-zero if
619                uv_stop() was called and there are still active handles or re‐
620                quests.  Returns zero in all other cases.
621
622              • UV_RUN_ONCE: Poll for i/o once. Note that this function blocks
623                if there are no pending callbacks. Returns zero when done  (no
624                active  handles  or  requests left), or non-zero if more call‐
625                backs are expected (meaning you  should  run  the  event  loop
626                again sometime in the future).
627
628              • UV_RUN_NOWAIT:  Poll for i/o once but don't block if there are
629                no pending callbacks. Returns zero if done (no active  handles
630                or  requests left), or non-zero if more callbacks are expected
631                (meaning you should run the event loop again sometime  in  the
632                future).
633
634              uv_run()  is  not  reentrant. It must not be called from a call‐
635              back.
636
637       int uv_loop_alive(const uv_loop_t *loop)
638              Returns non-zero if there are referenced active handles,  active
639              requests or closing handles in the loop.
640
641       void uv_stop(uv_loop_t *loop)
642              Stop  the  event loop, causing uv_run() to end as soon as possi‐
643              ble. This will happen not sooner than the next  loop  iteration.
644              If  this  function  was called before blocking for i/o, the loop
645              won't block for i/o on this iteration.
646
647       size_t uv_loop_size(void)
648              Returns the size of the  uv_loop_t  structure.  Useful  for  FFI
649              binding writers who don't want to know the structure layout.
650
651       int uv_backend_fd(const uv_loop_t *loop)
652              Get  backend file descriptor. Only kqueue, epoll and event ports
653              are supported.
654
655              This can be used in conjunction with uv_run(loop, UV_RUN_NOWAIT)
656              to  poll in one thread and run the event loop's callbacks in an‐
657              other see test/test-embed.c for an example.
658
659              NOTE:
660                 Embedding a kqueue fd in another kqueue pollset doesn't  work
661                 on  all  platforms.  It's  not  an error to add the fd but it
662                 never generates events.
663
664       int uv_backend_timeout(const uv_loop_t *loop)
665              Get the poll timeout. The return value is in milliseconds, or -1
666              for no timeout.
667
668       uint64_t uv_now(const uv_loop_t *loop)
669              Return  the  current timestamp in milliseconds. The timestamp is
670              cached at the start of the event loop tick, see uv_update_time()
671              for details and rationale.
672
673              The  timestamp increases monotonically from some arbitrary point
674              in time.  Don't make assumptions about the starting  point,  you
675              will only get disappointed.
676
677              NOTE:
678                 Use uv_hrtime() if you need sub-millisecond granularity.
679
680       void uv_update_time(uv_loop_t *loop)
681              Update  the event loop's concept of "now". Libuv caches the cur‐
682              rent time at the start of the event loop tick in order to reduce
683              the number of time-related system calls.
684
685              You  won't  normally  need to call this function unless you have
686              callbacks that block the event loop for longer periods of  time,
687              where  "longer" is somewhat subjective but probably on the order
688              of a millisecond or more.
689
690       void uv_walk(uv_loop_t *loop, uv_walk_cb walk_cb, void *arg)
691              Walk the list of handles: walk_cb  will  be  executed  with  the
692              given arg.
693
694       int uv_loop_fork(uv_loop_t *loop)
695              New in version 1.12.0.
696
697
698              Reinitialize any kernel state necessary in the child process af‐
699              ter a fork(2) system call.
700
701              Previously started watchers will continue to be started  in  the
702              child process.
703
704              It  is necessary to explicitly call this function on every event
705              loop created in the parent process that you plan to continue  to
706              use  in the child, including the default loop (even if you don't
707              continue to use it in the parent). This function must be  called
708              before calling uv_run() or any other API function using the loop
709              in the child. Failure to do so will result in  undefined  behav‐
710              iour, possibly including duplicate events delivered to both par‐
711              ent and child or aborting the child process.
712
713              When possible, it is preferred to create a new loop in the child
714              process  instead  of  reusing  a loop created in the parent. New
715              loops created in the child process after the fork should not use
716              this function.
717
718              This  function  is  not implemented on Windows, where it returns
719              UV_ENOSYS.
720
721              CAUTION:
722                 This function is experimental. It may contain  bugs,  and  is
723                 subject  to  change  or removal. API and ABI stability is not
724                 guaranteed.
725
726              NOTE:
727                 On Mac OS X, if directory FS event handles were in use in the
728                 parent  process for any event loop, the child process will no
729                 longer be able to use the most efficient FSEvent  implementa‐
730                 tion.  Instead,  uses  of  directory  FS event handles in the
731                 child will fall back to  the  same  implementation  used  for
732                 files and on other kqueue-based systems.
733
734              CAUTION:
735                 On  AIX and SunOS, FS event handles that were already started
736                 in the parent process at the time of forking will not deliver
737                 events  in  the  child  process;  they  must  be  closed  and
738                 restarted.  On all other platforms,  they  will  continue  to
739                 work normally without any further intervention.
740
741              CAUTION:
742                 Any  previous  value returned from uv_backend_fd() is now in‐
743                 valid. That function must be called again  to  determine  the
744                 correct backend file descriptor.
745
746       void *uv_loop_get_data(const uv_loop_t *loop)
747              Returns loop->data.
748
749              New in version 1.19.0.
750
751
752       void *uv_loop_set_data(uv_loop_t *loop, void *data)
753              Sets loop->data to data.
754
755              New in version 1.19.0.
756
757
758   uv_handle_t --- Base handle
759       uv_handle_t is the base type for all libuv handle types.
760
761       Structures  are aligned so that any libuv handle can be cast to uv_han‐
762       dle_t.  All API functions defined here work with any handle type.
763
764       Libuv handles are not movable. Pointers to handle structures passed  to
765       functions  must  remain  valid for the duration of the requested opera‐
766       tion. Take care when using stack allocated handles.
767
768   Data types
769       type uv_handle_t
770              The base libuv handle type.
771
772       enum uv_handle_type
773              The kind of the libuv handle.
774
775                 typedef enum {
776                   UV_UNKNOWN_HANDLE = 0,
777                   UV_ASYNC,
778                   UV_CHECK,
779                   UV_FS_EVENT,
780                   UV_FS_POLL,
781                   UV_HANDLE,
782                   UV_IDLE,
783                   UV_NAMED_PIPE,
784                   UV_POLL,
785                   UV_PREPARE,
786                   UV_PROCESS,
787                   UV_STREAM,
788                   UV_TCP,
789                   UV_TIMER,
790                   UV_TTY,
791                   UV_UDP,
792                   UV_SIGNAL,
793                   UV_FILE,
794                   UV_HANDLE_TYPE_MAX
795                 } uv_handle_type;
796
797       type uv_any_handle
798              Union of all handle types.
799
800       typedef void (*uv_alloc_cb)(uv_handle_t *handle, size_t suggested_size,
801       uv_buf_t *buf)
802              Type  definition  for  callback  passed  to  uv_read_start() and
803              uv_udp_recv_start(). The user must allocate memory and fill  the
804              supplied uv_buf_t structure. If NULL is assigned as the buffer's
805              base or 0 as its length, a UV_ENOBUFS error will be triggered in
806              the uv_udp_recv_cb or the uv_read_cb callback.
807
808              Each  buffer  is  used only once and the user is responsible for
809              freeing it in the uv_udp_recv_cb or the uv_read_cb callback.
810
811              A suggested size (65536 at the moment in  most  cases)  is  pro‐
812              vided,  but  it's  just an indication, not related in any way to
813              the pending data to be read. The user is free  to  allocate  the
814              amount of memory they decide.
815
816              As  an example, applications with custom allocation schemes such
817              as using freelists, allocation pools or  slab  based  allocators
818              may  decide  to  use  a  different size which matches the memory
819              chunks they already have.
820
821              Example:
822
823                 static void my_alloc_cb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
824                   buf->base = malloc(suggested_size);
825                   buf->len = suggested_size;
826                 }
827
828       typedef void (*uv_close_cb)(uv_handle_t *handle)
829              Type definition for callback passed to uv_close().
830
831   Public members
832       uv_loop_t *uv_handle_t.loop
833              Pointer to the uv_loop_t the handle is running on. Readonly.
834
835       uv_handle_type uv_handle_t.type
836              The uv_handle_type, indicating the type of the  underlying  han‐
837              dle. Readonly.
838
839       void *uv_handle_t.data
840              Space  for  user-defined arbitrary data. libuv does not use this
841              field.
842
843   API
844       UV_HANDLE_TYPE_MAP(iter_macro)
845              Macro that expands to a series of invocations of iter_macro  for
846              each  of  the handle types. iter_macro is invoked with two argu‐
847              ments: the name of the uv_handle_type element  without  the  UV_
848              prefix, and the name of the corresponding structure type without
849              the uv_ prefix and _t suffix.
850
851       int uv_is_active(const uv_handle_t *handle)
852              Returns non-zero if the handle is active, zero if it's inactive.
853              What "active" means depends on the type of handle:
854
855              • A  uv_async_t  handle  is  always active and cannot be deacti‐
856                vated, except by closing it with uv_close().
857
858              • A uv_pipe_t, uv_tcp_t, uv_udp_t, etc. handle -  basically  any
859                handle  that deals with i/o - is active when it is doing some‐
860                thing that involves i/o, like  reading,  writing,  connecting,
861                accepting new connections, etc.
862
863              • A  uv_check_t,  uv_idle_t,  uv_timer_t,  etc. handle is active
864                when it has been started  with  a  call  to  uv_check_start(),
865                uv_idle_start(), etc.
866
867              Rule of thumb: if a handle of type uv_foo_t has a uv_foo_start()
868              function, then it's active from  the  moment  that  function  is
869              called.  Likewise, uv_foo_stop() deactivates the handle again.
870
871       int uv_is_closing(const uv_handle_t *handle)
872              Returns non-zero if the handle is closing or closed, zero other‐
873              wise.
874
875              NOTE:
876                 This function should only be used between the  initialization
877                 of the handle and the arrival of the close callback.
878
879       void uv_close(uv_handle_t *handle, uv_close_cb close_cb)
880              Request  handle  to  be  closed.  close_cb  will be called asyn‐
881              chronously after this call. This MUST be called on  each  handle
882              before memory is released.  Moreover, the memory can only be re‐
883              leased in close_cb or after it has returned.
884
885              Handles that wrap file descriptors are  closed  immediately  but
886              close_cb  will  still  be  deferred to the next iteration of the
887              event loop.  It gives you a chance to free up any resources  as‐
888              sociated with the handle.
889
890              In-progress  requests, like uv_connect_t or uv_write_t, are can‐
891              celled and have their callbacks called asynchronously with  sta‐
892              tus=UV_ECANCELED.
893
894              close_cb  can  be NULL in cases where no cleanup or deallocation
895              is necessary.
896
897       void uv_ref(uv_handle_t *handle)
898              Reference the given handle. References are idempotent, that  is,
899              if  a  handle  is already referenced calling this function again
900              will have no effect.
901
902              See Reference counting.
903
904       void uv_unref(uv_handle_t *handle)
905              Un-reference the given handle. References are  idempotent,  that
906              is,  if  a  handle is not referenced calling this function again
907              will have no effect.
908
909              See Reference counting.
910
911       int uv_has_ref(const uv_handle_t *handle)
912              Returns non-zero if the handle referenced, zero otherwise.
913
914              See Reference counting.
915
916       size_t uv_handle_size(uv_handle_type type)
917              Returns the size of the given handle type. Useful for FFI  bind‐
918              ing writers who don't want to know the structure layout.
919
920   Miscellaneous API functions
921       The  following  API functions take a uv_handle_t argument but they work
922       just for some handle types.
923
924       int uv_send_buffer_size(uv_handle_t *handle, int *value)
925              Gets or sets the size of the send buffer that the operating sys‐
926              tem uses for the socket.
927
928              If *value == 0, then it will set *value to the current send buf‐
929              fer size.  If *value > 0 then it will use *value to set the  new
930              send buffer size.
931
932              On success, zero is returned. On error, a negative result is re‐
933              turned.
934
935              This function works for TCP, pipe and UDP handles  on  Unix  and
936              for TCP and UDP handles on Windows.
937
938              NOTE:
939                 Linux  will set double the size and return double the size of
940                 the original set value.
941
942       int uv_recv_buffer_size(uv_handle_t *handle, int *value)
943              Gets or sets the size of the receive buffer that  the  operating
944              system uses for the socket.
945
946              If  *value  == 0, then it will set *value to the current receive
947              buffer size.  If *value > 0 then it will use *value to  set  the
948              new receive buffer size.
949
950              On success, zero is returned. On error, a negative result is re‐
951              turned.
952
953              This function works for TCP, pipe and UDP handles  on  Unix  and
954              for TCP and UDP handles on Windows.
955
956              NOTE:
957                 Linux  will set double the size and return double the size of
958                 the original set value.
959
960       int uv_fileno(const uv_handle_t *handle, uv_os_fd_t *fd)
961              Gets the platform dependent file descriptor equivalent.
962
963              The following handles are supported: TCP, pipes,  TTY,  UDP  and
964              poll. Passing any other handle type will fail with UV_EINVAL.
965
966              If  a handle doesn't have an attached file descriptor yet or the
967              handle  itself  has  been  closed,  this  function  will  return
968              UV_EBADF.
969
970              WARNING:
971                 Be  very careful when using this function. libuv assumes it's
972                 in control of the file descriptor so any  change  to  it  may
973                 lead to malfunction.
974
975       uv_loop_t *uv_handle_get_loop(const uv_handle_t *handle)
976              Returns handle->loop.
977
978              New in version 1.19.0.
979
980
981       void *uv_handle_get_data(const uv_handle_t *handle)
982              Returns handle->data.
983
984              New in version 1.19.0.
985
986
987       void *uv_handle_set_data(uv_handle_t *handle, void *data)
988              Sets handle->data to data.
989
990              New in version 1.19.0.
991
992
993       uv_handle_type uv_handle_get_type(const uv_handle_t *handle)
994              Returns handle->type.
995
996              New in version 1.19.0.
997
998
999       const char *uv_handle_type_name(uv_handle_type type)
1000              Returns  the  name  for the equivalent struct for a given handle
1001              type, e.g. "pipe" (as in uv_pipe_t) for UV_NAMED_PIPE.
1002
1003              If no such handle type exists, this returns NULL.
1004
1005              New in version 1.19.0.
1006
1007
1008   Reference counting
1009       The libuv event loop (if run in the default mode) will run until  there
1010       are  no active and referenced handles left. The user can force the loop
1011       to exit early by unreferencing handles which are active, for example by
1012       calling uv_unref() after calling uv_timer_start().
1013
1014       A  handle  can  be  referenced  or unreferenced, the refcounting scheme
1015       doesn't use a counter, so both operations are idempotent.
1016
1017       All handles are referenced when active by default,  see  uv_is_active()
1018       for a more detailed explanation on what being active involves.
1019
1020   uv_req_t --- Base request
1021       uv_req_t is the base type for all libuv request types.
1022
1023       Structures  are  aligned  so  that  any  libuv  request  can be cast to
1024       uv_req_t.  All API functions defined here work with any request type.
1025
1026   Data types
1027       type uv_req_t
1028              The base libuv request structure.
1029
1030       type uv_any_req
1031              Union of all request types.
1032
1033   Public members
1034       void *uv_req_t.data
1035              Space for user-defined arbitrary data. libuv does not  use  this
1036              field.
1037
1038       uv_req_type uv_req_t.type
1039              Indicated the type of request. Readonly.
1040
1041                 typedef enum {
1042                     UV_UNKNOWN_REQ = 0,
1043                     UV_REQ,
1044                     UV_CONNECT,
1045                     UV_WRITE,
1046                     UV_SHUTDOWN,
1047                     UV_UDP_SEND,
1048                     UV_FS,
1049                     UV_WORK,
1050                     UV_GETADDRINFO,
1051                     UV_GETNAMEINFO,
1052                     UV_REQ_TYPE_MAX,
1053                 } uv_req_type;
1054
1055   API
1056       UV_REQ_TYPE_MAP(iter_macro)
1057              Macro  that expands to a series of invocations of iter_macro for
1058              each of the request types. iter_macro is invoked with two  argu‐
1059              ments:  the name of the uv_req_type element without the UV_ pre‐
1060              fix, and the name of the corresponding  structure  type  without
1061              the uv_ prefix and _t suffix.
1062
1063       int uv_cancel(uv_req_t *req)
1064              Cancel  a  pending request. Fails if the request is executing or
1065              has finished executing.
1066
1067              Returns 0 on success, or an error code < 0 on failure.
1068
1069              Only     cancellation     of     uv_fs_t,      uv_getaddrinfo_t,
1070              uv_getnameinfo_t,  uv_random_t  and  uv_work_t  requests is cur‐
1071              rently supported.
1072
1073              Cancelled requests have their callbacks invoked some time in the
1074              future.   It's  not  safe to free the memory associated with the
1075              request until the callback is called.
1076
1077              Here is how cancellation is reported to the callback:
1078
1079              • A uv_fs_t request has its req->result field  set  to  UV_ECAN‐
1080                CELED.
1081
1082              • A uv_work_t, uv_getaddrinfo_t, uv_getnameinfo_t or uv_random_t
1083                request has its callback invoked with status == UV_ECANCELED.
1084
1085       size_t uv_req_size(uv_req_type type)
1086              Returns the size of the given request type. Useful for FFI bind‐
1087              ing writers who don't want to know the structure layout.
1088
1089       void *uv_req_get_data(const uv_req_t *req)
1090              Returns req->data.
1091
1092              New in version 1.19.0.
1093
1094
1095       void *uv_req_set_data(uv_req_t *req, void *data)
1096              Sets req->data to data.
1097
1098              New in version 1.19.0.
1099
1100
1101       uv_req_type uv_req_get_type(const uv_req_t *req)
1102              Returns req->type.
1103
1104              New in version 1.19.0.
1105
1106
1107       const char *uv_req_type_name(uv_req_type type)
1108              Returns  the  name for the equivalent struct for a given request
1109              type, e.g. "connect" (as in uv_connect_t) for UV_CONNECT.
1110
1111              If no such request type exists, this returns NULL.
1112
1113              New in version 1.19.0.
1114
1115
1116   uv_timer_t --- Timer handle
1117       Timer handles are used to schedule callbacks to be called  in  the  fu‐
1118       ture.
1119
1120   Data types
1121       type uv_timer_t
1122              Timer handle type.
1123
1124       typedef void (*uv_timer_cb)(uv_timer_t *handle)
1125              Type definition for callback passed to uv_timer_start().
1126
1127   Public members
1128       N/A
1129
1130       SEE ALSO:
1131          The uv_handle_t members also apply.
1132
1133   API
1134       int uv_timer_init(uv_loop_t *loop, uv_timer_t *handle)
1135              Initialize the handle.
1136
1137       int  uv_timer_start(uv_timer_t  *handle, uv_timer_cb cb, uint64_t time‐
1138       out, uint64_t repeat)
1139              Start the timer. timeout and repeat are in milliseconds.
1140
1141              If timeout is zero, the callback fires on the  next  event  loop
1142              iteration.   If repeat is non-zero, the callback fires first af‐
1143              ter timeout milliseconds and then repeatedly after  repeat  mil‐
1144              liseconds.
1145
1146              NOTE:
1147                 Does  not  update  the  event  loop's  concept  of "now". See
1148                 uv_update_time() for more information.
1149
1150                 If the timer is already active, it is simply updated.
1151
1152       int uv_timer_stop(uv_timer_t *handle)
1153              Stop the timer, the callback will not be called anymore.
1154
1155       int uv_timer_again(uv_timer_t *handle)
1156              Stop the timer, and if it is repeating restart it using the  re‐
1157              peat  value  as the timeout. If the timer has never been started
1158              before it returns UV_EINVAL.
1159
1160       void uv_timer_set_repeat(uv_timer_t *handle, uint64_t repeat)
1161              Set the repeat interval value in milliseconds. The timer will be
1162              scheduled  to run on the given interval, regardless of the call‐
1163              back execution duration, and will follow normal timer  semantics
1164              in the case of a time-slice overrun.
1165
1166              For  example,  if a 50ms repeating timer first runs for 17ms, it
1167              will be scheduled to run again 33ms later. If other  tasks  con‐
1168              sume more than the 33ms following the first timer callback, then
1169              the callback will run as soon as possible.
1170
1171              NOTE:
1172                 If the repeat value is set from a timer callback it does  not
1173                 immediately  take effect.  If the timer was non-repeating be‐
1174                 fore, it will have been stopped. If it  was  repeating,  then
1175                 the old repeat value will have been used to schedule the next
1176                 timeout.
1177
1178       uint64_t uv_timer_get_repeat(const uv_timer_t *handle)
1179              Get the timer repeat value.
1180
1181       uint64_t uv_timer_get_due_in(const uv_timer_t *handle)
1182              Get the timer due value or 0 if it has expired. The time is rel‐
1183              ative to uv_now().
1184
1185              New in version 1.40.0.
1186
1187
1188       SEE ALSO:
1189          The uv_handle_t API functions also apply.
1190
1191   uv_prepare_t --- Prepare handle
1192       Prepare  handles  will  run the given callback once per loop iteration,
1193       right before polling for i/o.
1194
1195   Data types
1196       type uv_prepare_t
1197              Prepare handle type.
1198
1199       typedef void (*uv_prepare_cb)(uv_prepare_t *handle)
1200              Type definition for callback passed to uv_prepare_start().
1201
1202   Public members
1203       N/A
1204
1205       SEE ALSO:
1206          The uv_handle_t members also apply.
1207
1208   API
1209       int uv_prepare_init(uv_loop_t *loop, uv_prepare_t *prepare)
1210              Initialize the handle. This function always succeeds.
1211
1212              Returns
1213                     0
1214
1215       int uv_prepare_start(uv_prepare_t *prepare, uv_prepare_cb cb)
1216              Start the handle with the given callback. This  function  always
1217              succeeds, except when cb is NULL.
1218
1219              Returns
1220                     0 on success, or UV_EINVAL when cb == NULL.
1221
1222       int uv_prepare_stop(uv_prepare_t *prepare)
1223              Stop  the  handle,  the callback will no longer be called.  This
1224              function always succeeds.
1225
1226              Returns
1227                     0
1228
1229       SEE ALSO:
1230          The uv_handle_t API functions also apply.
1231
1232   uv_check_t --- Check handle
1233       Check handles will run the given  callback  once  per  loop  iteration,
1234       right after polling for i/o.
1235
1236   Data types
1237       type uv_check_t
1238              Check handle type.
1239
1240       typedef void (*uv_check_cb)(uv_check_t *handle)
1241              Type definition for callback passed to uv_check_start().
1242
1243   Public members
1244       N/A
1245
1246       SEE ALSO:
1247          The uv_handle_t members also apply.
1248
1249   API
1250       int uv_check_init(uv_loop_t *loop, uv_check_t *check)
1251              Initialize the handle. This function always succeeds.
1252
1253              Returns
1254                     0
1255
1256       int uv_check_start(uv_check_t *check, uv_check_cb cb)
1257              Start  the  handle with the given callback. This function always
1258              succeeds, except when cb is NULL.
1259
1260              Returns
1261                     0 on success, or UV_EINVAL when cb == NULL.
1262
1263       int uv_check_stop(uv_check_t *check)
1264              Stop the handle, the callback will no longer  be  called.   This
1265              function always succeeds.
1266
1267              Returns
1268                     0
1269
1270       SEE ALSO:
1271          The uv_handle_t API functions also apply.
1272
1273   uv_idle_t --- Idle handle
1274       Idle handles will run the given callback once per loop iteration, right
1275       before the uv_prepare_t handles.
1276
1277       NOTE:
1278          The notable difference with prepare handles is that when  there  are
1279          active  idle  handles, the loop will perform a zero timeout poll in‐
1280          stead of blocking for i/o.
1281
1282       WARNING:
1283          Despite the name, idle handles will get their  callbacks  called  on
1284          every loop iteration, not when the loop is actually "idle".
1285
1286   Data types
1287       type uv_idle_t
1288              Idle handle type.
1289
1290       typedef void (*uv_idle_cb)(uv_idle_t *handle)
1291              Type definition for callback passed to uv_idle_start().
1292
1293   Public members
1294       N/A
1295
1296       SEE ALSO:
1297          The uv_handle_t members also apply.
1298
1299   API
1300       int uv_idle_init(uv_loop_t *loop, uv_idle_t *idle)
1301              Initialize the handle. This function always succeeds.
1302
1303              Returns
1304                     0
1305
1306       int uv_idle_start(uv_idle_t *idle, uv_idle_cb cb)
1307              Start  the  handle with the given callback. This function always
1308              succeeds, except when cb is NULL.
1309
1310              Returns
1311                     0 on success, or UV_EINVAL when cb == NULL.
1312
1313       int uv_idle_stop(uv_idle_t *idle)
1314              Stop the handle, the callback will no longer  be  called.   This
1315              function always succeeds.
1316
1317              Returns
1318                     0
1319
1320       SEE ALSO:
1321          The uv_handle_t API functions also apply.
1322
1323   uv_async_t --- Async handle
1324       Async handles allow the user to "wakeup" the event loop and get a call‐
1325       back called from another thread.
1326
1327   Data types
1328       type uv_async_t
1329              Async handle type.
1330
1331       typedef void (*uv_async_cb)(uv_async_t *handle)
1332              Type definition for callback passed to uv_async_init().
1333
1334   Public members
1335       N/A
1336
1337       SEE ALSO:
1338          The uv_handle_t members also apply.
1339
1340   API
1341       int  uv_async_init(uv_loop_t  *loop,  uv_async_t  *async,   uv_async_cb
1342       async_cb)
1343              Initialize the handle. A NULL callback is allowed.
1344
1345              Returns
1346                     0 on success, or an error code < 0 on failure.
1347
1348              NOTE:
1349                 Unlike other handle initialization  functions, it immediately
1350                 starts the handle.
1351
1352       int uv_async_send(uv_async_t *async)
1353              Wake up the event loop and call the async handle's callback.
1354
1355              Returns
1356                     0 on success, or an error code < 0 on failure.
1357
1358              NOTE:
1359                 It's safe to call this function from any thread. The callback
1360                 will be called on the loop thread.
1361
1362              NOTE:
1363                 uv_async_send() is async-signal-safe.  It's safe to call this
1364                 function from a signal handler.
1365
1366              WARNING:
1367                 libuv will coalesce calls to uv_async_send(),  that  is,  not
1368                 every call to it will yield an execution of the callback. For
1369                 example: if uv_async_send() is called 5 times in a row before
1370                 the  callback  is  called,  the  callback will only be called
1371                 once. If uv_async_send() is called again after  the  callback
1372                 was called, it will be called again.
1373
1374       SEE ALSO:
1375          The uv_handle_t API functions also apply.
1376
1377   uv_poll_t --- Poll handle
1378       Poll  handles  are  used  to  watch  file  descriptors for readability,
1379       writability and disconnection similar to the purpose of poll(2).
1380
1381       The purpose of poll handles is to enable integrating external libraries
1382       that  rely  on  the  event  loop  to  signal it about the socket status
1383       changes, like c-ares or libssh2. Using uv_poll_t for any other  purpose
1384       is  not recommended; uv_tcp_t, uv_udp_t, etc. provide an implementation
1385       that is faster and  more  scalable  than  what  can  be  achieved  with
1386       uv_poll_t, especially on Windows.
1387
1388       It  is  possible  that poll handles occasionally signal that a file de‐
1389       scriptor is readable or writable even when it isn't.  The  user  should
1390       therefore always be prepared to handle EAGAIN or equivalent when it at‐
1391       tempts to read from or write to the fd.
1392
1393       It is not okay to have  multiple  active  poll  handles  for  the  same
1394       socket, this can cause libuv to busyloop or otherwise malfunction.
1395
1396       The user should not close a file descriptor while it is being polled by
1397       an active poll handle. This can cause the handle to  report  an  error,
1398       but  it  might also start polling another socket. However the fd can be
1399       safely closed immediately after a call to uv_poll_stop() or uv_close().
1400
1401       NOTE:
1402          On windows only sockets can be polled with poll handles. On Unix any
1403          file descriptor that would be accepted by poll(2) can be used.
1404
1405       NOTE:
1406          On AIX, watching for disconnection is not supported.
1407
1408   Data types
1409       type uv_poll_t
1410              Poll handle type.
1411
1412       typedef void (*uv_poll_cb)(uv_poll_t *handle, int status, int events)
1413              Type definition for callback passed to uv_poll_start().
1414
1415       type uv_poll_event
1416              Poll event types
1417
1418                 enum uv_poll_event {
1419                     UV_READABLE = 1,
1420                     UV_WRITABLE = 2,
1421                     UV_DISCONNECT = 4,
1422                     UV_PRIORITIZED = 8
1423                 };
1424
1425   Public members
1426       N/A
1427
1428       SEE ALSO:
1429          The uv_handle_t members also apply.
1430
1431   API
1432       int uv_poll_init(uv_loop_t *loop, uv_poll_t *handle, int fd)
1433              Initialize the handle using a file descriptor.
1434
1435              Changed  in  version  1.2.2:  the  file  descriptor  is  set  to
1436              non-blocking mode.
1437
1438
1439       int    uv_poll_init_socket(uv_loop_t    *loop,    uv_poll_t    *handle,
1440       uv_os_sock_t socket)
1441              Initialize the handle using a socket descriptor. On Unix this is
1442              identical to uv_poll_init(). On windows it takes a  SOCKET  han‐
1443              dle.
1444
1445              Changed  in  version  1.2.2:  the  socket is set to non-blocking
1446              mode.
1447
1448
1449       int uv_poll_start(uv_poll_t *handle, int events, uv_poll_cb cb)
1450              Starts polling the file descriptor. events is a bitmask made  up
1451              of  UV_READABLE,  UV_WRITABLE, UV_PRIORITIZED and UV_DISCONNECT.
1452              As soon as an event is detected the callback will be called with
1453              status  set  to  0,  and  the  detected events set on the events
1454              field.
1455
1456              The UV_PRIORITIZED event is used to watch for  sysfs  interrupts
1457              or TCP out-of-band messages.
1458
1459              The UV_DISCONNECT event is optional in the sense that it may not
1460              be reported and the user is free to ignore it, but it  can  help
1461              optimize  the  shutdown path because an extra read or write call
1462              might be avoided.
1463
1464              If an error happens while polling, status will be < 0 and corre‐
1465              sponds  with  one of the UV_E* error codes (see Error handling).
1466              The user should not close the socket while the handle is active.
1467              If the user does that anyway, the callback may be called report‐
1468              ing an error status, but this is not guaranteed.  If  status  ==
1469              UV_EBADF polling is discontinued for the file handle and no fur‐
1470              ther  events  will  be  reported.  The  user  should  then  call
1471              uv_close() on the handle.
1472
1473              NOTE:
1474                 Calling uv_poll_start() on a handle that is already active is
1475                 fine. Doing so will update the  events  mask  that  is  being
1476                 watched for.
1477
1478              NOTE:
1479                 Though UV_DISCONNECT can be set, it is unsupported on AIX and
1480                 as such will not be set on the events field in the callback.
1481
1482              NOTE:
1483                 If one of the events UV_READABLE or UV_WRITABLE are set,  the
1484                 callback will be called again, as long as the given fd/socket
1485                 remains readable or  writable  accordingly.  Particularly  in
1486                 each of the following scenarios:
1487
1488                 • The  callback  has  been  called  because the socket became
1489                   readable/writable  and  the  callback  did  not  conduct  a
1490                   read/write on this socket at all.
1491
1492                 • The  callback  committed  a read on the socket, and has not
1493                   read all the available data (when UV_READABLE is set).
1494
1495                 • The callback committed a write on the socket,  but  it  re‐
1496                   mained writable afterwards (when UV_WRITABLE is set).
1497
1498                 • The  socket  has  already  became  readable/writable before
1499                   calling uv_poll_start() on a poll  handle  associated  with
1500                   this socket, and since then the state of the socket did not
1501                   changed.
1502
1503                 In all of the above  listed  scenarios,  the  socket  remains
1504                 readable  or  writable  and hence the callback will be called
1505                 again (depending on the events set in the bitmask). This  be‐
1506                 haviour is known as level triggering.
1507
1508              Changed in version 1.9.0: Added the UV_DISCONNECT event.
1509
1510
1511              Changed in version 1.14.0: Added the UV_PRIORITIZED event.
1512
1513
1514       int uv_poll_stop(uv_poll_t *poll)
1515              Stop polling the file descriptor, the callback will no longer be
1516              called.
1517
1518              NOTE:
1519                 Calling uv_poll_stop() is effective immediately: any  pending
1520                 callback  is  also  canceled, even if the socket state change
1521                 notification was already pending.
1522
1523       SEE ALSO:
1524          The uv_handle_t API functions also apply.
1525
1526   uv_signal_t --- Signal handle
1527       Signal handles implement Unix style signal handling on a per-event loop
1528       bases.
1529
1530   Windows notes
1531       Reception of some signals is emulated:
1532
1533       • SIGINT  is  normally delivered when the user presses CTRL+C. However,
1534         like on Unix, it is not generated when terminal raw mode is enabled.
1535
1536       • SIGBREAK is delivered when the user pressed CTRL + BREAK.
1537
1538       • SIGHUP is generated when the  user  closes  the  console  window.  On
1539         SIGHUP  the  program  is  given  approximately  10 seconds to perform
1540         cleanup. After that Windows will unconditionally terminate it.
1541
1542       • SIGWINCH is raised whenever libuv detects that the console  has  been
1543         resized.  When  a  libuv  app is running under a console emulator, or
1544         when a 32-bit libuv app is running on 64-bit system, SIGWINCH will be
1545         emulated.  In such cases SIGWINCH signals may not always be delivered
1546         in a timely manner.  For a writable uv_tty_t handle libuv  will  only
1547         detect  size  changes  when  the  cursor  is  moved.  When a readable
1548         uv_tty_t handle is used, resizing of the console buffer will  be  de‐
1549         tected only if the handle is in raw mode and is being read.
1550
1551       • Watchers  for  other  signals  can be successfully created, but these
1552         signals are never  received.  These  signals  are:  SIGILL,  SIGABRT,
1553         SIGFPE, SIGSEGV, SIGTERM and SIGKILL.
1554
1555       • Calls  to  raise()  or abort() to programmatically raise a signal are
1556         not detected by libuv; these will not trigger a signal watcher.
1557
1558       Changed in version 1.15.0: SIGWINCH support on Windows was improved.
1559
1560
1561       Changed in version 1.31.0: 32-bit libuv SIGWINCH support on 64-bit Win‐
1562       dows was rolled back to old implementation.
1563
1564
1565   Unix notes
1566       • SIGKILL and SIGSTOP are impossible to catch.
1567
1568       • Handling SIGBUS, SIGFPE, SIGILL or SIGSEGV via libuv results into un‐
1569         defined behavior.
1570
1571       • SIGABRT will not be caught by libuv if  generated  by  abort(),  e.g.
1572         through assert().
1573
1574       • On  Linux  SIGRT0 and SIGRT1 (signals 32 and 33) are used by the NPTL
1575         pthreads library to manage threads.  Installing  watchers  for  those
1576         signals  will lead to unpredictable behavior and is strongly discour‐
1577         aged. Future versions of libuv may simply reject them.
1578
1579   Data types
1580       type uv_signal_t
1581              Signal handle type.
1582
1583       typedef void (*uv_signal_cb)(uv_signal_t *handle, int signum)
1584              Type definition for callback passed to uv_signal_start().
1585
1586   Public members
1587       int uv_signal_t.signum
1588              Signal being monitored by this handle. Readonly.
1589
1590       SEE ALSO:
1591          The uv_handle_t members also apply.
1592
1593   API
1594       int uv_signal_init(uv_loop_t *loop, uv_signal_t *signal)
1595              Initialize the handle.
1596
1597       int uv_signal_start(uv_signal_t *signal, uv_signal_cb cb, int signum)
1598              Start the handle with the given callback, watching for the given
1599              signal.
1600
1601       int  uv_signal_start_oneshot(uv_signal_t  *signal, uv_signal_cb cb, int
1602       signum)
1603              New in version 1.12.0.
1604
1605
1606              Same functionality as uv_signal_start() but the  signal  handler
1607              is reset the moment the signal is received.
1608
1609       int uv_signal_stop(uv_signal_t *signal)
1610              Stop the handle, the callback will no longer be called.
1611
1612       SEE ALSO:
1613          The uv_handle_t API functions also apply.
1614
1615   uv_process_t --- Process handle
1616       Process  handles will spawn a new process and allow the user to control
1617       it and establish communication channels with it using streams.
1618
1619   Data types
1620       type uv_process_t
1621              Process handle type.
1622
1623       type uv_process_options_t
1624              Options for spawning the process (passed to uv_spawn().
1625
1626                 typedef struct uv_process_options_s {
1627                     uv_exit_cb exit_cb;
1628                     const char* file;
1629                     char** args;
1630                     char** env;
1631                     const char* cwd;
1632                     unsigned int flags;
1633                     int stdio_count;
1634                     uv_stdio_container_t* stdio;
1635                     uv_uid_t uid;
1636                     uv_gid_t gid;
1637                 } uv_process_options_t;
1638
1639       typedef  void  (*uv_exit_cb)(uv_process_t*,  int64_t  exit_status,  int
1640       term_signal)
1641              Type  definition  for  callback  passed  in uv_process_options_t
1642              which will indicate the exit status and the signal  that  caused
1643              the process to terminate, if any.
1644
1645       type uv_process_flags
1646              Flags to be set on the flags field of uv_process_options_t.
1647
1648                 enum uv_process_flags {
1649                     /*
1650                     * Set the child process' user id.
1651                     */
1652                     UV_PROCESS_SETUID = (1 << 0),
1653                     /*
1654                     * Set the child process' group id.
1655                     */
1656                     UV_PROCESS_SETGID = (1 << 1),
1657                     /*
1658                     * Do not wrap any arguments in quotes, or perform any other escaping, when
1659                     * converting the argument list into a command line string. This option is
1660                     * only meaningful on Windows systems. On Unix it is silently ignored.
1661                     */
1662                     UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = (1 << 2),
1663                     /*
1664                     * Spawn the child process in a detached state - this will make it a process
1665                     * group leader, and will effectively enable the child to keep running after
1666                     * the parent exits. Note that the child process will still keep the
1667                     * parent's event loop alive unless the parent process calls uv_unref() on
1668                     * the child's process handle.
1669                     */
1670                     UV_PROCESS_DETACHED = (1 << 3),
1671                     /*
1672                     * Hide the subprocess window that would normally be created. This option is
1673                     * only meaningful on Windows systems. On Unix it is silently ignored.
1674                     */
1675                     UV_PROCESS_WINDOWS_HIDE = (1 << 4),
1676                     /*
1677                     * Hide the subprocess console window that would normally be created. This
1678                     * option is only meaningful on Windows systems. On Unix it is silently
1679                     * ignored.
1680                     */
1681                     UV_PROCESS_WINDOWS_HIDE_CONSOLE = (1 << 5),
1682                     /*
1683                     * Hide the subprocess GUI window that would normally be created. This
1684                     * option is only meaningful on Windows systems. On Unix it is silently
1685                     * ignored.
1686                     */
1687                     UV_PROCESS_WINDOWS_HIDE_GUI = (1 << 6)
1688                 };
1689
1690       type uv_stdio_container_t
1691              Container for each stdio handle or fd passed to a child process.
1692
1693                 typedef struct uv_stdio_container_s {
1694                     uv_stdio_flags flags;
1695                     union {
1696                         uv_stream_t* stream;
1697                         int fd;
1698                     } data;
1699                 } uv_stdio_container_t;
1700
1701       enum uv_stdio_flags
1702              Flags  specifying how a stdio should be transmitted to the child
1703              process.
1704
1705                 typedef enum {
1706                     /*
1707                     * The following four options are mutually-exclusive, and define
1708                     * the operation to perform for the corresponding file descriptor
1709                     * in the child process:
1710                     */
1711
1712                     /*
1713                     * No file descriptor will be provided (or redirected to
1714                     * `/dev/null` if it is fd 0, 1 or 2).
1715                     */
1716                     UV_IGNORE = 0x00,
1717
1718                     /*
1719                     * Open a new pipe into `data.stream`, per the flags below. The
1720                     * `data.stream` field must point to a uv_pipe_t object that has
1721                     * been initialized with `uv_pipe_init(loop, data.stream, ipc);`,
1722                     * but not yet opened or connected.
1723                     /*
1724                     UV_CREATE_PIPE = 0x01,
1725
1726                     /*
1727                     * The child process will be given a duplicate of the parent's
1728                     * file descriptor given by `data.fd`.
1729                     */
1730                     UV_INHERIT_FD = 0x02,
1731
1732                     /*
1733                     * The child process will be given a duplicate of the parent's
1734                     * file descriptor being used by the stream handle given by
1735                     * `data.stream`.
1736                     */
1737                     UV_INHERIT_STREAM = 0x04,
1738
1739                     /*
1740                     * When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE
1741                     * determine the direction of flow, from the child process' perspective. Both
1742                     * flags may be specified to create a duplex data stream.
1743                     */
1744                     UV_READABLE_PIPE = 0x10,
1745                     UV_WRITABLE_PIPE = 0x20,
1746
1747                     /*
1748                     * When UV_CREATE_PIPE is specified, specifying UV_NONBLOCK_PIPE opens the
1749                     * handle in non-blocking mode in the child. This may cause loss of data,
1750                     * if the child is not designed to handle to encounter this mode,
1751                     * but can also be significantly more efficient.
1752                     */
1753                     UV_NONBLOCK_PIPE = 0x40
1754                 } uv_stdio_flags;
1755
1756   Public members
1757       int uv_process_t.pid
1758              The  PID  of  the  spawned  process.  It's  set  after   calling
1759              uv_spawn().
1760
1761       NOTE:
1762          The uv_handle_t members also apply.
1763
1764       uv_exit_cb uv_process_options_t.exit_cb
1765              Callback called after the process exits.
1766
1767       const char *uv_process_options_t.file
1768              Path pointing to the program to be executed.
1769
1770       char **uv_process_options_t.args
1771              Command  line  arguments. args[0] should be the path to the pro‐
1772              gram. On Windows this uses CreateProcess which concatenates  the
1773              arguments  into a string this can cause some strange errors. See
1774              the      UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS      flag      on
1775              uv_process_flags.
1776
1777       char **uv_process_options_t.env
1778              Environment for the new process. If NULL the parents environment
1779              is used.
1780
1781       const char *uv_process_options_t.cwd
1782              Current working directory for the subprocess.
1783
1784       unsigned int uv_process_options_t.flags
1785              Various  flags  that  control  how   uv_spawn()   behaves.   See
1786              uv_process_flags.
1787
1788       int uv_process_options_t.stdio_count
1789
1790       uv_stdio_container_t *uv_process_options_t.stdio
1791              The  stdio  field  points  to  an  array of uv_stdio_container_t
1792              structs that describe the file descriptors  that  will  be  made
1793              available  to the child process. The convention is that stdio[0]
1794              points to stdin, fd 1 is used for stdout, and fd 2 is stderr.
1795
1796              NOTE:
1797                 On Windows file descriptors greater than 2 are  available  to
1798                 the child process only if the child processes uses the MSVCRT
1799                 runtime.
1800
1801       uv_uid_t uv_process_options_t.uid
1802
1803       uv_gid_t uv_process_options_t.gid
1804              Libuv can change the child process' user/group id. This  happens
1805              only when the appropriate bits are set in the flags fields.
1806
1807              NOTE:
1808                 This  is  not  supported on Windows, uv_spawn() will fail and
1809                 set the error to UV_ENOTSUP.
1810
1811       uv_stdio_flags uv_stdio_container_t.flags
1812              Flags specifying how the stdio container should be passed to the
1813              child.
1814
1815       union [anonymous] uv_stdio_container_t.data
1816              Union  containing either the stream or fd to be passed on to the
1817              child process.
1818
1819   API
1820       void uv_disable_stdio_inheritance(void)
1821              Disables inheritance for file descriptors /  handles  that  this
1822              process inherited from its parent. The effect is that child pro‐
1823              cesses spawned by this process don't accidentally inherit  these
1824              handles.
1825
1826              It is recommended to call this function as early in your program
1827              as possible, before the inherited file descriptors can be closed
1828              or duplicated.
1829
1830              NOTE:
1831                 This function works on a best-effort basis: there is no guar‐
1832                 antee that libuv can discover all file descriptors that  were
1833                 inherited. In general it does a better job on Windows than it
1834                 does on Unix.
1835
1836       int   uv_spawn(uv_loop_t    *loop,    uv_process_t    *handle,    const
1837       uv_process_options_t *options)
1838              Initializes  the  process  handle and starts the process. If the
1839              process is successfully spawned, this function  will  return  0.
1840              Otherwise,  the  negative error code corresponding to the reason
1841              it couldn't spawn is returned.
1842
1843              Possible reasons for failing to spawn would include (but not  be
1844              limited to) the file to execute not existing, not having permis‐
1845              sions to use the setuid  or  setgid  specified,  or  not  having
1846              enough memory to allocate for the new process.
1847
1848              Changed in version 1.24.0: Added UV_PROCESS_WINDOWS_HIDE_CONSOLE
1849              and UV_PROCESS_WINDOWS_HIDE_GUI flags.
1850
1851
1852       int uv_process_kill(uv_process_t *handle, int signum)
1853              Sends the specified signal to the given  process  handle.  Check
1854              the  documentation  on  uv_signal_t --- Signal handle for signal
1855              support, specially on Windows.
1856
1857       int uv_kill(int pid, int signum)
1858              Sends the specified signal to the given PID. Check the  documen‐
1859              tation on uv_signal_t --- Signal handle for signal support, spe‐
1860              cially on Windows.
1861
1862       uv_pid_t uv_process_get_pid(const uv_process_t *handle)
1863              Returns handle->pid.
1864
1865              New in version 1.19.0.
1866
1867
1868       SEE ALSO:
1869          The uv_handle_t API functions also apply.
1870
1871   uv_stream_t --- Stream handle
1872       Stream handles provide an abstraction of a duplex  communication  chan‐
1873       nel.   uv_stream_t  is an abstract type, libuv provides 3 stream imple‐
1874       mentations in the form of uv_tcp_t, uv_pipe_t and uv_tty_t.
1875
1876   Data types
1877       type uv_stream_t
1878              Stream handle type.
1879
1880       type uv_connect_t
1881              Connect request type.
1882
1883       type uv_shutdown_t
1884              Shutdown request type.
1885
1886       type uv_write_t
1887              Write request type. Careful attention must be paid when  reusing
1888              objects  of  this  type.  When a stream is in non-blocking mode,
1889              write requests sent with uv_write will be  queued.  Reusing  ob‐
1890              jects  at this point is undefined behaviour. It is safe to reuse
1891              the uv_write_t object only after the callback passed to uv_write
1892              is fired.
1893
1894       typedef  void  (*uv_read_cb)(uv_stream_t  *stream, ssize_t nread, const
1895       uv_buf_t *buf)
1896              Callback called when data was read on a stream.
1897
1898              nread is > 0 if there is data available or < 0  on  error.  When
1899              we've  reached EOF, nread will be set to UV_EOF. When nread < 0,
1900              the buf parameter might not point to a  valid  buffer;  in  that
1901              case buf.len and buf.base are both set to 0.
1902
1903              NOTE:
1904                 nread  might  be  0, which does not indicate an error or EOF.
1905                 This is equivalent to EAGAIN or EWOULDBLOCK under read(2).
1906
1907              The callee is responsible for stopping/closing the  stream  when
1908              an error happens by calling uv_read_stop() or uv_close(). Trying
1909              to read from the stream again is undefined.
1910
1911              The callee is responsible for freeing the buffer, libuv does not
1912              reuse  it.   The buffer may be a null buffer (where buf->base ==
1913              NULL and buf->len == 0) on error.
1914
1915       typedef void (*uv_write_cb)(uv_write_t *req, int status)
1916              Callback called after data was written on a stream. status  will
1917              be 0 in case of success, < 0 otherwise.
1918
1919       typedef void (*uv_connect_cb)(uv_connect_t *req, int status)
1920              Callback  called  after  a connection started by uv_connect() is
1921              done.  status will be 0 in case of success, < 0 otherwise.
1922
1923       typedef void (*uv_shutdown_cb)(uv_shutdown_t *req, int status)
1924              Callback called after a shutdown  request  has  been  completed.
1925              status will be 0 in case of success, < 0 otherwise.
1926
1927       typedef void (*uv_connection_cb)(uv_stream_t *server, int status)
1928              Callback  called  when  a stream server has received an incoming
1929              connection.  The user  can  accept  the  connection  by  calling
1930              uv_accept().   status  will  be 0 in case of success, < 0 other‐
1931              wise.
1932
1933   Public members
1934       size_t uv_stream_t.write_queue_size
1935              Contains the amount of queued bytes waiting to  be  sent.  Read‐
1936              only.
1937
1938       uv_stream_t *uv_connect_t.handle
1939              Pointer to the stream where this connection request is running.
1940
1941       uv_stream_t *uv_shutdown_t.handle
1942              Pointer to the stream where this shutdown request is running.
1943
1944       uv_stream_t *uv_write_t.handle
1945              Pointer to the stream where this write request is running.
1946
1947       uv_stream_t *uv_write_t.send_handle
1948              Pointer to the stream being sent using this write request.
1949
1950       SEE ALSO:
1951          The uv_handle_t members also apply.
1952
1953   API
1954       int uv_shutdown(uv_shutdown_t *req, uv_stream_t *handle, uv_shutdown_cb
1955       cb)
1956              Shutdown the outgoing (write) side of a duplex stream. It  waits
1957              for  pending write requests to complete. The handle should refer
1958              to a initialized stream.  req should be an  uninitialized  shut‐
1959              down  request  struct.  The  cb is called after shutdown is com‐
1960              plete.
1961
1962       int uv_listen(uv_stream_t *stream, int backlog, uv_connection_cb cb)
1963              Start listening for incoming connections. backlog indicates  the
1964              number of connections the kernel might queue, same as listen(2).
1965              When a new incoming connection is received the  uv_connection_cb
1966              callback is called.
1967
1968       int uv_accept(uv_stream_t *server, uv_stream_t *client)
1969              This  call is used in conjunction with uv_listen() to accept in‐
1970              coming  connections.  Call  this  function  after  receiving   a
1971              uv_connection_cb  to  accept the connection. Before calling this
1972              function the client handle must be initialized. < 0 return value
1973              indicates an error.
1974
1975              When  the  uv_connection_cb  callback is called it is guaranteed
1976              that this function will complete successfully the first time. If
1977              you  attempt  to  use it more than once, it may fail. It is sug‐
1978              gested to only call  this  function  once  per  uv_connection_cb
1979              call.
1980
1981              NOTE:
1982                 server and client must be handles running on the same loop.
1983
1984       int uv_read_start(uv_stream_t *stream, uv_alloc_cb alloc_cb, uv_read_cb
1985       read_cb)
1986              Read data from an incoming stream. The uv_read_cb callback  will
1987              be  made  several  times  until there is no more data to read or
1988              uv_read_stop() is called.
1989
1990              Changed in version 1.38.0: uv_read_start() now consistently  re‐
1991              turns  UV_EALREADY  when  called  twice,  and UV_EINVAL when the
1992              stream is closing. With older libuv versions, it returns UV_EAL‐
1993              READY  on  Windows  but  not UNIX, and UV_EINVAL on UNIX but not
1994              Windows.
1995
1996
1997       int uv_read_stop(uv_stream_t*)
1998              Stop reading data from the stream. The uv_read_cb callback  will
1999              no longer be called.
2000
2001              This  function  is  idempotent  and  may  be  safely called on a
2002              stopped stream.
2003
2004              This function will always succeed; hence,  checking  its  return
2005              value is unnecessary. A non-zero return indicates that finishing
2006              releasing resources may be pending on the next  input  event  on
2007              that TTY on Windows, and does not indicate failure.
2008
2009       int  uv_write(uv_write_t  *req,  uv_stream_t  *handle,  const  uv_buf_t
2010       bufs[], unsigned int nbufs, uv_write_cb cb)
2011              Write data to stream. Buffers are written in order. Example:
2012
2013                 void cb(uv_write_t* req, int status) {
2014                     /* Logic which handles the write result */
2015                 }
2016
2017                 uv_buf_t a[] = {
2018                     { .base = "1", .len = 1 },
2019                     { .base = "2", .len = 1 }
2020                 };
2021
2022                 uv_buf_t b[] = {
2023                     { .base = "3", .len = 1 },
2024                     { .base = "4", .len = 1 }
2025                 };
2026
2027                 uv_write_t req1;
2028                 uv_write_t req2;
2029
2030                 /* writes "1234" */
2031                 uv_write(&req1, stream, a, 2, cb);
2032                 uv_write(&req2, stream, b, 2, cb);
2033
2034              NOTE:
2035                 The memory pointed to by the buffers must remain valid  until
2036                 the callback gets called.  This also holds for uv_write2().
2037
2038       int  uv_write2(uv_write_t  *req,  uv_stream_t  *handle,  const uv_buf_t
2039       bufs[], unsigned int nbufs, uv_stream_t *send_handle, uv_write_cb cb)
2040              Extended write function for sending handles  over  a  pipe.  The
2041              pipe must be initialized with ipc == 1.
2042
2043              NOTE:
2044                 send_handle  must be a TCP, pipe and UDP handle on Unix, or a
2045                 TCP handle on Windows, which is  a  server  or  a  connection
2046                 (listening  or  connected state). Bound sockets or pipes will
2047                 be assumed to be servers.
2048
2049       int uv_try_write(uv_stream_t *handle, const uv_buf_t  bufs[],  unsigned
2050       int nbufs)
2051              Same  as uv_write(), but won't queue a write request if it can't
2052              be completed immediately.
2053
2054              Will return either:
2055
2056              • > 0: number of bytes written (can be less  than  the  supplied
2057                buffer size).
2058
2059              • < 0: negative error code (UV_EAGAIN is returned if no data can
2060                be sent immediately).
2061
2062       int uv_try_write2(uv_stream_t *handle, const uv_buf_t bufs[],  unsigned
2063       int nbufs, uv_stream_t *send_handle)
2064              Same  as  uv_try_write() and extended write function for sending
2065              handles over a pipe like c:func:uv_write2.
2066
2067              Try to send a handle is not supported on Windows, where  it  re‐
2068              turns UV_EAGAIN.
2069
2070              New in version 1.42.0.
2071
2072
2073       int uv_is_readable(const uv_stream_t *handle)
2074              Returns 1 if the stream is readable, 0 otherwise.
2075
2076       int uv_is_writable(const uv_stream_t *handle)
2077              Returns 1 if the stream is writable, 0 otherwise.
2078
2079       int uv_stream_set_blocking(uv_stream_t *handle, int blocking)
2080              Enable or disable blocking mode for a stream.
2081
2082              When blocking mode is enabled all writes complete synchronously.
2083              The interface remains unchanged otherwise,  e.g.  completion  or
2084              failure  of the operation will still be reported through a call‐
2085              back which is made asynchronously.
2086
2087              WARNING:
2088                 Relying too much on this API is not recommended. It is likely
2089                 to change significantly in the future.
2090
2091                 Currently  only  works  on Windows for uv_pipe_t handles.  On
2092                 UNIX platforms, all uv_stream_t handles are supported.
2093
2094                 Also libuv currently makes no  ordering  guarantee  when  the
2095                 blocking  mode  is  changed after write requests have already
2096                 been submitted. Therefore it is recommended to set the block‐
2097                 ing mode immediately after opening or creating the stream.
2098
2099              Changed in version 1.4.0: UNIX implementation added.
2100
2101
2102       size_t uv_stream_get_write_queue_size(const uv_stream_t *stream)
2103              Returns stream->write_queue_size.
2104
2105              New in version 1.19.0.
2106
2107
2108       SEE ALSO:
2109          The uv_handle_t API functions also apply.
2110
2111   uv_tcp_t --- TCP handle
2112       TCP handles are used to represent both TCP streams and servers.
2113
2114       uv_tcp_t is a 'subclass' of uv_stream_t.
2115
2116   Data types
2117       type uv_tcp_t
2118              TCP handle type.
2119
2120   Public members
2121       N/A
2122
2123       SEE ALSO:
2124          The uv_stream_t members also apply.
2125
2126   API
2127       int uv_tcp_init(uv_loop_t *loop, uv_tcp_t *handle)
2128              Initialize the handle. No socket is created as of yet.
2129
2130       int  uv_tcp_init_ex(uv_loop_t  *loop,  uv_tcp_t  *handle,  unsigned int
2131       flags)
2132              Initialize the handle with the specified flags.  At  the  moment
2133              only  the  lower  8  bits of the flags parameter are used as the
2134              socket domain. A socket will be created for the given domain. If
2135              the  specified  domain  is  AF_UNSPEC no socket is created, just
2136              like uv_tcp_init().
2137
2138              New in version 1.7.0.
2139
2140
2141       int uv_tcp_open(uv_tcp_t *handle, uv_os_sock_t sock)
2142              Open an existing file descriptor or SOCKET as a TCP handle.
2143
2144              Changed  in  version  1.2.1:  the  file  descriptor  is  set  to
2145              non-blocking mode.
2146
2147
2148              NOTE:
2149                 The  passed  file descriptor or SOCKET is not checked for its
2150                 type, but it's required that it  represents  a  valid  stream
2151                 socket.
2152
2153       int uv_tcp_nodelay(uv_tcp_t *handle, int enable)
2154              Enable TCP_NODELAY, which disables Nagle's algorithm.
2155
2156       int uv_tcp_keepalive(uv_tcp_t *handle, int enable, unsigned int delay)
2157              Enable  /  disable TCP keep-alive. delay is the initial delay in
2158              seconds, ignored when enable is zero.
2159
2160              After delay has been reached, 10 successive probes, each  spaced
2161              1  second  from the previous one, will still happen. If the con‐
2162              nection is still lost at the end of  this  procedure,  then  the
2163              handle is destroyed with a UV_ETIMEDOUT error passed to the cor‐
2164              responding callback.
2165
2166       int uv_tcp_simultaneous_accepts(uv_tcp_t *handle, int enable)
2167              Enable / disable simultaneous asynchronous accept requests  that
2168              are  queued  by  the operating system when listening for new TCP
2169              connections.
2170
2171              This setting is used to tune a TCP server for the  desired  per‐
2172              formance.  Having simultaneous accepts can significantly improve
2173              the rate of accepting connections (which is why it is enabled by
2174              default)   but   may   lead   to  uneven  load  distribution  in
2175              multi-process setups.
2176
2177       int uv_tcp_bind(uv_tcp_t *handle, const struct sockaddr *addr, unsigned
2178       int flags)
2179              Bind  the handle to an address and port. addr should point to an
2180              initialized struct sockaddr_in or struct sockaddr_in6.
2181
2182              When the port is already taken, you can expect to see an UV_EAD‐
2183              DRINUSE  error  from uv_listen() or uv_tcp_connect(). That is, a
2184              successful call to this function does  not  guarantee  that  the
2185              call to uv_listen() or uv_tcp_connect() will succeed as well.
2186
2187              flags can contain UV_TCP_IPV6ONLY, in which case dual-stack sup‐
2188              port is disabled and only IPv6 is used.
2189
2190       int uv_tcp_getsockname(const uv_tcp_t *handle, struct  sockaddr  *name,
2191       int *namelen)
2192              Get  the current address to which the handle is bound. name must
2193              point to a valid and big enough chunk of  memory,  struct  sock‐
2194              addr_storage is recommended for IPv4 and IPv6 support.
2195
2196       int  uv_tcp_getpeername(const  uv_tcp_t *handle, struct sockaddr *name,
2197       int *namelen)
2198              Get the address of the peer connected to the handle.  name  must
2199              point  to  a  valid and big enough chunk of memory, struct sock‐
2200              addr_storage is recommended for IPv4 and IPv6 support.
2201
2202       int uv_tcp_connect(uv_connect_t *req, uv_tcp_t  *handle,  const  struct
2203       sockaddr *addr, uv_connect_cb cb)
2204              Establish an IPv4 or IPv6 TCP connection. Provide an initialized
2205              TCP handle and an uninitialized uv_connect_t. addr should  point
2206              to an initialized struct sockaddr_in or struct sockaddr_in6.
2207
2208              On Windows if the addr is initialized to point to an unspecified
2209              address (0.0.0.0 or ::) it will be changed to  point  to  local‐
2210              host.  This is done to match the behavior of Linux systems.
2211
2212              The callback is made when the connection has been established or
2213              when a connection error happened.
2214
2215              Changed in version 1.19.0: added 0.0.0.0  and  ::  to  localhost
2216              mapping
2217
2218
2219       SEE ALSO:
2220          The uv_stream_t API functions also apply.
2221
2222       int uv_tcp_close_reset(uv_tcp_t *handle, uv_close_cb close_cb)
2223              Resets  a TCP connection by sending a RST packet. This is accom‐
2224              plished by setting the SO_LINGER socket option with a linger in‐
2225              terval  of  zero and then calling uv_close().  Due to some plat‐
2226              form    inconsistencies,    mixing    of    uv_shutdown()    and
2227              uv_tcp_close_reset() calls is not allowed.
2228
2229              New in version 1.32.0.
2230
2231
2232       int  uv_socketpair(int  type,  int  protocol,  uv_os_sock_t socket_vec‐
2233       tor[2], int flags0, int flags1)
2234              Create a pair of connected sockets with  the  specified  proper‐
2235              ties.   The resulting handles can be passed to uv_tcp_open, used
2236              with uv_spawn, or for any other purpose.
2237
2238              Valid values for flags0 and flags1 are:
2239
2240                 • UV_NONBLOCK_PIPE: Opens the  specified  socket  handle  for
2241                   OVERLAPPED or FIONBIO/O_NONBLOCK I/O usage.  This is recom‐
2242                   mended for handles that will be used by libuv, and not usu‐
2243                   ally recommended otherwise.
2244
2245              Equivalent to socketpair(2) with a domain of AF_UNIX.
2246
2247              New in version 1.41.0.
2248
2249
2250   uv_pipe_t --- Pipe handle
2251       Pipe  handles  provide an abstraction over streaming files on Unix (in‐
2252       cluding local domain sockets, pipes, and FIFOs) and named pipes on Win‐
2253       dows.
2254
2255       uv_pipe_t is a 'subclass' of uv_stream_t.
2256
2257   Data types
2258       type uv_pipe_t
2259              Pipe handle type.
2260
2261   Public members
2262       int uv_pipe_t.ipc
2263              Whether  this  pipe  is suitable for handle passing between pro‐
2264              cesses.  Only a connected pipe that will be passing the  handles
2265              should have this flag set, not the listening pipe that uv_accept
2266              is called on.
2267
2268       SEE ALSO:
2269          The uv_stream_t members also apply.
2270
2271   API
2272       int uv_pipe_init(uv_loop_t *loop, uv_pipe_t *handle, int ipc)
2273              Initialize a pipe handle. The ipc argument is a boolean to indi‐
2274              cate  if  this pipe will be used for handle passing between pro‐
2275              cesses (which may change the bytes on the  wire).  Only  a  con‐
2276              nected  pipe  that  will be passing the handles should have this
2277              flag set, not the listening pipe that uv_accept is called on.
2278
2279       int uv_pipe_open(uv_pipe_t *handle, uv_file file)
2280              Open an existing file descriptor or HANDLE as a pipe.
2281
2282              Changed  in  version  1.2.1:  the  file  descriptor  is  set  to
2283              non-blocking mode.
2284
2285
2286              NOTE:
2287                 The  passed  file descriptor or HANDLE is not checked for its
2288                 type, but it's required that it represents a valid pipe.
2289
2290       int uv_pipe_bind(uv_pipe_t *handle, const char *name)
2291              Bind the pipe to a file path (Unix) or a name (Windows).
2292
2293              Does  not  support  Linux  abstract  namespace  sockets,  unlike
2294              uv_pipe_bind2().
2295
2296              Alias for uv_pipe_bind2(handle, name, strlen(name), 0).
2297
2298              NOTE:
2299                 Paths  on  Unix get truncated to sizeof(sockaddr_un.sun_path)
2300                 bytes, typically between 92 and 108 bytes.
2301
2302       int uv_pipe_bind2(uv_pipe_t *handle, const char *name, size_t  namelen,
2303       unsigned int flags)
2304              Bind the pipe to a file path (Unix) or a name (Windows).
2305
2306              flags must be zero or UV_PIPE_NO_TRUNCATE. Returns UV_EINVAL for
2307              unsupported flags without performing the bind operation.
2308
2309              Supports Linux abstract namespace sockets. namelen must  include
2310              the leading nul byte but not the trailing nul byte.
2311
2312              New in version 1.46.0.
2313
2314
2315              NOTE:
2316                 Paths  on  Unix get truncated to sizeof(sockaddr_un.sun_path)
2317                 bytes,  typically  between  92  and  108  bytes,  unless  the
2318                 UV_PIPE_NO_TRUNCATE  flag  is  specified,  in  which  case an
2319                 UV_EINVAL error is returned.
2320
2321       void uv_pipe_connect(uv_connect_t *req, uv_pipe_t *handle,  const  char
2322       *name, uv_connect_cb cb)
2323              Connect to the Unix domain socket or the Windows named pipe.
2324
2325              Does  not  support  Linux  abstract  namespace  sockets,  unlike
2326              uv_pipe_connect2().
2327
2328              Alias for uv_pipe_connect2(req, handle, name,  strlen(name),  0,
2329              cb).
2330
2331              NOTE:
2332                 Paths  on  Unix get truncated to sizeof(sockaddr_un.sun_path)
2333                 bytes, typically between 92 and 108 bytes.
2334
2335       void uv_pipe_connect2(uv_connect_t *req, uv_pipe_t *handle, const  char
2336       *name, size_t namelen, unsigned int flags, uv_connect_cb cb)
2337              Connect to the Unix domain socket or the Windows named pipe.
2338
2339              flags must be zero or UV_PIPE_NO_TRUNCATE. Returns UV_EINVAL for
2340              unsupported flags without performing the connect operation.
2341
2342              Supports Linux abstract namespace sockets. namelen must  include
2343              the leading nul byte but not the trailing nul byte.
2344
2345              New in version 1.46.0.
2346
2347
2348              NOTE:
2349                 Paths  on  Unix get truncated to sizeof(sockaddr_un.sun_path)
2350                 bytes,  typically  between  92  and  108  bytes,  unless  the
2351                 UV_PIPE_NO_TRUNCATE  flag  is  specified,  in  which  case an
2352                 UV_EINVAL error is returned.
2353
2354       int uv_pipe_getsockname(const uv_pipe_t *handle, char  *buffer,  size_t
2355       *size)
2356              Get the name of the Unix domain socket or the named pipe.
2357
2358              A preallocated buffer must be provided. The size parameter holds
2359              the length of the buffer and it's set to  the  number  of  bytes
2360              written to the buffer on output. If the buffer is not big enough
2361              UV_ENOBUFS will be returned and len will  contain  the  required
2362              size.
2363
2364              Changed in version 1.3.0: the returned length no longer includes
2365              the terminating null byte, and the buffer  is  not  null  termi‐
2366              nated.
2367
2368
2369       int  uv_pipe_getpeername(const  uv_pipe_t *handle, char *buffer, size_t
2370       *size)
2371              Get the name of the Unix domain socket  or  the  named  pipe  to
2372              which the handle is connected.
2373
2374              A preallocated buffer must be provided. The size parameter holds
2375              the length of the buffer and it's set to  the  number  of  bytes
2376              written to the buffer on output. If the buffer is not big enough
2377              UV_ENOBUFS will be returned and len will  contain  the  required
2378              size.
2379
2380              New in version 1.3.0.
2381
2382
2383       void uv_pipe_pending_instances(uv_pipe_t *handle, int count)
2384              Set  the  number  of pending pipe instance handles when the pipe
2385              server is waiting for connections.
2386
2387              NOTE:
2388                 This setting applies to Windows only.
2389
2390       int uv_pipe_pending_count(uv_pipe_t *handle)
2391
2392       uv_handle_type uv_pipe_pending_type(uv_pipe_t *handle)
2393              Used to receive handles over IPC pipes.
2394
2395              First - call uv_pipe_pending_count(), if it's > 0 then  initial‐
2396              ize    a    handle    of    the    given   type,   returned   by
2397              uv_pipe_pending_type() and call uv_accept(pipe, handle).
2398
2399       SEE ALSO:
2400          The uv_stream_t API functions also apply.
2401
2402       int uv_pipe_chmod(uv_pipe_t *handle, int flags)
2403              Alters pipe permissions, allowing it to be  accessed  from  pro‐
2404              cesses  run by different users. Makes the pipe writable or read‐
2405              able by all users.  Mode  can  be  UV_WRITABLE,  UV_READABLE  or
2406              UV_WRITABLE | UV_READABLE. This function is blocking.
2407
2408              New in version 1.16.0.
2409
2410
2411       int uv_pipe(uv_file fds[2], int read_flags, int write_flags)
2412              Create a pair of connected pipe handles.  Data may be written to
2413              fds[1] and read from  fds[0].   The  resulting  handles  can  be
2414              passed  to  uv_pipe_open,  used  with uv_spawn, or for any other
2415              purpose.
2416
2417              Valid values for flags are:
2418
2419                 • UV_NONBLOCK_PIPE: Opens the  specified  socket  handle  for
2420                   OVERLAPPED or FIONBIO/O_NONBLOCK I/O usage.  This is recom‐
2421                   mended for handles that will be used by libuv, and not usu‐
2422                   ally recommended otherwise.
2423
2424              Equivalent to pipe(2) with the O_CLOEXEC flag set.
2425
2426              New in version 1.41.0.
2427
2428
2429   uv_tty_t --- TTY handle
2430       TTY handles represent a stream for the console.
2431
2432       uv_tty_t is a 'subclass' of uv_stream_t.
2433
2434   Data types
2435       type uv_tty_t
2436              TTY handle type.
2437
2438       enum uv_tty_mode_t
2439              New in version 1.2.0.
2440
2441
2442              TTY mode type:
2443
2444                 typedef enum {
2445                     /* Initial/normal terminal mode */
2446                     UV_TTY_MODE_NORMAL,
2447                     /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */
2448                     UV_TTY_MODE_RAW,
2449                     /* Binary-safe I/O mode for IPC (Unix-only) */
2450                     UV_TTY_MODE_IO
2451                 } uv_tty_mode_t;
2452
2453       enum uv_tty_vtermstate_t
2454              Console virtual terminal mode type:
2455
2456                 typedef enum {
2457                     /*
2458                      * The console supports handling of virtual terminal sequences
2459                      * (Windows10 new console, ConEmu)
2460                      */
2461                     UV_TTY_SUPPORTED,
2462                     /* The console cannot process virtual terminal sequences.  (Legacy
2463                      * console)
2464                      */
2465                     UV_TTY_UNSUPPORTED
2466                 } uv_tty_vtermstate_t
2467
2468   Public members
2469       N/A
2470
2471       SEE ALSO:
2472          The uv_stream_t members also apply.
2473
2474   API
2475       int  uv_tty_init(uv_loop_t *loop, uv_tty_t *handle, uv_file fd, int un‐
2476       used)
2477              Initialize a new TTY stream with the given file descriptor. Usu‐
2478              ally the file descriptor will be:
2479
2480              • 0 = stdin
2481
2482              • 1 = stdout
2483
2484              • 2 = stderr
2485
2486              On  Unix  this function will determine the path of the fd of the
2487              terminal using ttyname_r(3), open it, and use it if  the  passed
2488              file  descriptor refers to a TTY. This lets libuv put the tty in
2489              non-blocking mode without affecting other processes  that  share
2490              the tty.
2491
2492              This  function  is not thread safe on systems that don't support
2493              ioctl TIOCGPTN or TIOCPTYGNAME, for  instance  OpenBSD  and  So‐
2494              laris.
2495
2496              NOTE:
2497                 If  reopening  the  TTY  fails,  libuv falls back to blocking
2498                 writes.
2499
2500              Changed in version 1.23.1:: the readable parameter is now unused
2501              and  ignored.   The correct value will now be auto-detected from
2502              the kernel.
2503
2504
2505              Changed in version 1.9.0:: the path of the TTY is determined  by
2506              ttyname_r(3). In earlier versions libuv opened /dev/tty instead.
2507
2508
2509              Changed  in  version  1.5.0::  trying to initialize a TTY stream
2510              with a file descriptor that refers to a file  returns  UV_EINVAL
2511              on UNIX.
2512
2513
2514       int uv_tty_set_mode(uv_tty_t *handle, uv_tty_mode_t mode)
2515              Changed   in   version  1.2.0::  the  mode  is  specified  as  a
2516              uv_tty_mode_t value.
2517
2518
2519              Set the TTY using the specified terminal mode.
2520
2521       int uv_tty_reset_mode(void)
2522              To be called when the program exits. Resets TTY settings to  de‐
2523              fault values for the next process to take over.
2524
2525              This  function  is  async  signal-safe on Unix platforms but can
2526              fail with error code UV_EBUSY if you call it when  execution  is
2527              inside uv_tty_set_mode().
2528
2529       int uv_tty_get_winsize(uv_tty_t *handle, int *width, int *height)
2530              Gets the current Window size. On success it returns 0.
2531
2532       SEE ALSO:
2533          The uv_stream_t API functions also apply.
2534
2535       void uv_tty_set_vterm_state(uv_tty_vtermstate_t state)
2536              Controls  whether  console  virtual  terminal sequences are pro‐
2537              cessed by libuv or console.  Useful in particular  for  enabling
2538              ConEmu  support  of  ANSI  X3.64 and Xterm 256 colors. Otherwise
2539              Windows10 consoles are usually detected automatically.
2540
2541              This function is only meaningful on Windows systems. On Unix  it
2542              is silently ignored.
2543
2544              New in version 1.33.0.
2545
2546
2547       int uv_tty_get_vterm_state(uv_tty_vtermstate_t *state)
2548              Get  the  current  state of whether console virtual terminal se‐
2549              quences are handled by libuv or the console.
2550
2551              This function is not  implemented  on  Unix,  where  it  returns
2552              UV_ENOTSUP.
2553
2554              New in version 1.33.0.
2555
2556
2557   uv_udp_t --- UDP handle
2558       UDP handles encapsulate UDP communication for both clients and servers.
2559
2560   Data types
2561       type uv_udp_t
2562              UDP handle type.
2563
2564       type uv_udp_send_t
2565              UDP send request type.
2566
2567       type uv_udp_flags
2568              Flags used in uv_udp_bind() and uv_udp_recv_cb..
2569
2570                 enum uv_udp_flags {
2571                     /* Disables dual stack mode. */
2572                     UV_UDP_IPV6ONLY = 1,
2573                     /*
2574                     * Indicates message was truncated because read buffer was too small. The
2575                     * remainder was discarded by the OS. Used in uv_udp_recv_cb.
2576                     */
2577                     UV_UDP_PARTIAL = 2,
2578                     /*
2579                     * Indicates if SO_REUSEADDR will be set when binding the handle in
2580                     * uv_udp_bind.
2581                     * This sets the SO_REUSEPORT socket flag on the BSDs and OS X. On other
2582                     * Unix platforms, it sets the SO_REUSEADDR flag. What that means is that
2583                     * multiple threads or processes can bind to the same address without error
2584                     * (provided they all set the flag) but only the last one to bind will receive
2585                     * any traffic, in effect "stealing" the port from the previous listener.
2586                     */
2587                     UV_UDP_REUSEADDR = 4,
2588                     /*
2589                      * Indicates that the message was received by recvmmsg, so the buffer provided
2590                      * must not be freed by the recv_cb callback.
2591                      */
2592                     UV_UDP_MMSG_CHUNK = 8,
2593                     /*
2594                      * Indicates that the buffer provided has been fully utilized by recvmmsg and
2595                      * that it should now be freed by the recv_cb callback. When this flag is set
2596                      * in uv_udp_recv_cb, nread will always be 0 and addr will always be NULL.
2597                      */
2598                     UV_UDP_MMSG_FREE = 16,
2599                     /*
2600                      * Indicates if IP_RECVERR/IPV6_RECVERR will be set when binding the handle.
2601                      * This sets IP_RECVERR for IPv4 and IPV6_RECVERR for IPv6 UDP sockets on
2602                      * Linux. This stops the Linux kernel from suppressing some ICMP error messages
2603                      * and enables full ICMP error reporting for faster failover.
2604                      * This flag is no-op on platforms other than Linux.
2605                      */
2606                     UV_UDP_LINUX_RECVERR = 32,
2607                     /*
2608                     * Indicates that recvmmsg should be used, if available.
2609                     */
2610                     UV_UDP_RECVMMSG = 256
2611                 };
2612
2613       typedef void (*uv_udp_send_cb)(uv_udp_send_t *req, int status)
2614              Type  definition  for callback passed to uv_udp_send(), which is
2615              called after the data was sent.
2616
2617       typedef void (*uv_udp_recv_cb)(uv_udp_t *handle, ssize_t  nread,  const
2618       uv_buf_t *buf, const struct sockaddr *addr, unsigned flags)
2619              Type  definition  for  callback  passed  to uv_udp_recv_start(),
2620              which is called when the endpoint receives data.
2621
2622handle: UDP handle
2623
2624nread:  Number of bytes that have been received.  0  if  there
2625                is  no  more  data  to read. Note that 0 may also mean that an
2626                empty datagram was received (in this case addr is not NULL). <
2627                0  if  a transmission error was detected; if using recvmmsg(2)
2628                no more chunks will be received and the buffer  can  be  freed
2629                safely.
2630
2631buf: uv_buf_t with the received data.
2632
2633addr:  struct  sockaddr* containing the address of the sender.
2634                Can be NULL. Valid for the duration of the callback only.
2635
2636flags: One or more or'ed UV_UDP_* constants.
2637
2638              The callee is responsible for freeing the buffer, libuv does not
2639              reuse  it.   The buffer may be a null buffer (where buf->base ==
2640              NULL and buf->len == 0) on error.
2641
2642              When using recvmmsg(2), chunks will have  the  UV_UDP_MMSG_CHUNK
2643              flag  set,  those  must  not be freed. If no errors occur, there
2644              will be a final callback with nread set to 0, addr set  to  NULL
2645              and the buffer pointing at the initially allocated data with the
2646              UV_UDP_MMSG_CHUNK flag cleared  and  the  UV_UDP_MMSG_FREE  flag
2647              set.  If a UDP socket error occurs, nread will be < 0. In either
2648              scenario, the callee can now safely free the provided buffer.
2649
2650              Changed in version 1.40.0: added the UV_UDP_MMSG_FREE flag.
2651
2652
2653              NOTE:
2654                 The receive callback will be called with nread == 0 and  addr
2655                 ==  NULL  when  there is nothing to read, and with nread == 0
2656                 and addr != NULL when an empty UDP packet is received.
2657
2658       enum uv_membership
2659              Membership type for a multicast address.
2660
2661                 typedef enum {
2662                     UV_LEAVE_GROUP = 0,
2663                     UV_JOIN_GROUP
2664                 } uv_membership;
2665
2666   Public members
2667       size_t uv_udp_t.send_queue_size
2668              Number of bytes queued for sending. This  field  strictly  shows
2669              how much information is currently queued.
2670
2671       size_t uv_udp_t.send_queue_count
2672              Number  of  send  requests currently in the queue awaiting to be
2673              processed.
2674
2675       uv_udp_t *uv_udp_send_t.handle
2676              UDP handle where this send request is taking place.
2677
2678       SEE ALSO:
2679          The uv_handle_t members also apply.
2680
2681   API
2682       int uv_udp_init(uv_loop_t *loop, uv_udp_t *handle)
2683              Initialize a new  UDP  handle.  The  actual  socket  is  created
2684              lazily.  Returns 0 on success.
2685
2686       int  uv_udp_init_ex(uv_loop_t  *loop,  uv_udp_t  *handle,  unsigned int
2687       flags)
2688              Initialize the handle with the specified flags. The lower 8 bits
2689              of  the  flags parameter are used as the socket domain. A socket
2690              will be created for the given domain.  If the  specified  domain
2691              is AF_UNSPEC no socket is created, just like uv_udp_init().
2692
2693              The remaining bits can be used to set one of these flags:
2694
2695UV_UDP_RECVMMSG:   if  set,  and  the  platform  supports  it,
2696                recvmmsg(2) will be used.
2697
2698              New in version 1.7.0.
2699
2700
2701              Changed in version 1.37.0: added the UV_UDP_RECVMMSG flag.
2702
2703
2704       int uv_udp_open(uv_udp_t *handle, uv_os_sock_t sock)
2705              Opens an existing file descriptor or Windows  SOCKET  as  a  UDP
2706              handle.
2707
2708              Unix  only: The only requirement of the sock argument is that it
2709              follows the datagram contract (works in unconnected  mode,  sup‐
2710              ports  sendmsg()/recvmsg(),  etc).   In other words, other data‐
2711              gram-type sockets like raw sockets or netlink sockets  can  also
2712              be passed to this function.
2713
2714              Changed  in  version  1.2.1:  the  file  descriptor  is  set  to
2715              non-blocking mode.
2716
2717
2718              NOTE:
2719                 The passed file descriptor or SOCKET is not checked  for  its
2720                 type,  but  it's required that it represents a valid datagram
2721                 socket.
2722
2723       int uv_udp_bind(uv_udp_t *handle, const struct sockaddr *addr, unsigned
2724       int flags)
2725              Bind the UDP handle to an IP address and port.
2726
2727              Parameters
2728
2729handle -- UDP handle. Should have been initialized with
2730                       uv_udp_init().
2731
2732addr -- struct sockaddr_in or struct sockaddr_in6  with
2733                       the address and port to bind to.
2734
2735flags  --  Indicate  how  the  socket  will  be  bound,
2736                       UV_UDP_IPV6ONLY, UV_UDP_REUSEADDR,  and  UV_UDP_RECVERR
2737                       are supported.
2738
2739              Returns
2740                     0 on success, or an error code < 0 on failure.
2741
2742       int uv_udp_connect(uv_udp_t *handle, const struct sockaddr *addr)
2743              Associate  the UDP handle to a remote address and port, so every
2744              message sent by this handle is automatically sent to that desti‐
2745              nation.   Calling this function with a NULL addr disconnects the
2746              handle.  Trying to call uv_udp_connect() on an already connected
2747              handle  will result in an UV_EISCONN error. Trying to disconnect
2748              a handle that is not connected will return an UV_ENOTCONN error.
2749
2750              Parameters
2751
2752handle -- UDP handle. Should have been initialized with
2753                       uv_udp_init().
2754
2755addr  -- struct sockaddr_in or struct sockaddr_in6 with
2756                       the address and port to associate to.
2757
2758              Returns
2759                     0 on success, or an error code < 0 on failure.
2760
2761              New in version 1.27.0.
2762
2763
2764       int uv_udp_getpeername(const uv_udp_t *handle, struct  sockaddr  *name,
2765       int *namelen)
2766              Get  the  remote  IP and port of the UDP handle on connected UDP
2767              handles.  On unconnected handles, it returns UV_ENOTCONN.
2768
2769              Parameters
2770
2771handle -- UDP handle. Should have been initialized with
2772                       uv_udp_init() and bound.
2773
2774name  -- Pointer to the structure to be filled with the
2775                       address data.  In order to support IPv4 and IPv6 struct
2776                       sockaddr_storage should be used.
2777
2778namelen  --  On input it indicates the data of the name
2779                       field. On output  it  indicates  how  much  of  it  was
2780                       filled.
2781
2782              Returns
2783                     0 on success, or an error code < 0 on failure
2784
2785              New in version 1.27.0.
2786
2787
2788       int  uv_udp_getsockname(const  uv_udp_t *handle, struct sockaddr *name,
2789       int *namelen)
2790              Get the local IP and port of the UDP handle.
2791
2792              Parameters
2793
2794handle -- UDP handle. Should have been initialized with
2795                       uv_udp_init() and bound.
2796
2797name  -- Pointer to the structure to be filled with the
2798                       address data.  In order to support IPv4 and IPv6 struct
2799                       sockaddr_storage should be used.
2800
2801namelen  --  On input it indicates the data of the name
2802                       field. On output  it  indicates  how  much  of  it  was
2803                       filled.
2804
2805              Returns
2806                     0 on success, or an error code < 0 on failure.
2807
2808       int uv_udp_set_membership(uv_udp_t *handle, const char *multicast_addr,
2809       const char *interface_addr, uv_membership membership)
2810              Set membership for a multicast address
2811
2812              Parameters
2813
2814handle -- UDP handle. Should have been initialized with
2815                       uv_udp_init().
2816
2817multicast_addr  --  Multicast address to set membership
2818                       for.
2819
2820interface_addr -- Interface address.
2821
2822membership    --    Should    be    UV_JOIN_GROUP    or
2823                       UV_LEAVE_GROUP.
2824
2825              Returns
2826                     0 on success, or an error code < 0 on failure.
2827
2828       int  uv_udp_set_source_membership(uv_udp_t  *handle, const char *multi‐
2829       cast_addr,  const  char  *interface_addr,  const   char   *source_addr,
2830       uv_membership membership)
2831              Set membership for a source-specific multicast group.
2832
2833              Parameters
2834
2835handle -- UDP handle. Should have been initialized with
2836                       uv_udp_init().
2837
2838multicast_addr -- Multicast address to  set  membership
2839                       for.
2840
2841interface_addr -- Interface address.
2842
2843source_addr -- Source address.
2844
2845membership    --    Should    be    UV_JOIN_GROUP    or
2846                       UV_LEAVE_GROUP.
2847
2848              Returns
2849                     0 on success, or an error code < 0 on failure.
2850
2851              New in version 1.32.0.
2852
2853
2854       int uv_udp_set_multicast_loop(uv_udp_t *handle, int on)
2855              Set IP multicast loop flag. Makes multicast packets loop back to
2856              local sockets.
2857
2858              Parameters
2859
2860handle -- UDP handle. Should have been initialized with
2861                       uv_udp_init().
2862
2863on -- 1 for on, 0 for off.
2864
2865              Returns
2866                     0 on success, or an error code < 0 on failure.
2867
2868       int uv_udp_set_multicast_ttl(uv_udp_t *handle, int ttl)
2869              Set the multicast ttl.
2870
2871              Parameters
2872
2873handle -- UDP handle. Should have been initialized with
2874                       uv_udp_init().
2875
2876ttl -- 1 through 255.
2877
2878              Returns
2879                     0 on success, or an error code < 0 on failure.
2880
2881       int uv_udp_set_multicast_interface(uv_udp_t *handle, const char *inter‐
2882       face_addr)
2883              Set the multicast interface to send or receive data on.
2884
2885              Parameters
2886
2887handle -- UDP handle. Should have been initialized with
2888                       uv_udp_init().
2889
2890interface_addr -- interface address.
2891
2892              Returns
2893                     0 on success, or an error code < 0 on failure.
2894
2895       int uv_udp_set_broadcast(uv_udp_t *handle, int on)
2896              Set broadcast on or off.
2897
2898              Parameters
2899
2900handle -- UDP handle. Should have been initialized with
2901                       uv_udp_init().
2902
2903on -- 1 for on, 0 for off.
2904
2905              Returns
2906                     0 on success, or an error code < 0 on failure.
2907
2908       int uv_udp_set_ttl(uv_udp_t *handle, int ttl)
2909              Set the time to live.
2910
2911              Parameters
2912
2913handle -- UDP handle. Should have been initialized with
2914                       uv_udp_init().
2915
2916ttl -- 1 through 255.
2917
2918              Returns
2919                     0 on success, or an error code < 0 on failure.
2920
2921       int  uv_udp_send(uv_udp_send_t  *req,  uv_udp_t *handle, const uv_buf_t
2922       bufs[], unsigned int nbufs, const struct sockaddr *addr, uv_udp_send_cb
2923       send_cb)
2924              Send  data over the UDP socket. If the socket has not previously
2925              been bound with uv_udp_bind() it will be bound to  0.0.0.0  (the
2926              "all interfaces" IPv4 address) and a random port number.
2927
2928              On Windows if the addr is initialized to point to an unspecified
2929              address (0.0.0.0 or ::) it will be changed to  point  to  local‐
2930              host.  This is done to match the behavior of Linux systems.
2931
2932              For  connected  UDP handles, addr must be set to NULL, otherwise
2933              it will return UV_EISCONN error.
2934
2935              For connectionless UDP handles, addr cannot be  NULL,  otherwise
2936              it will return UV_EDESTADDRREQ error.
2937
2938              Parameters
2939
2940req -- UDP request handle. Need not be initialized.
2941
2942handle -- UDP handle. Should have been initialized with
2943                       uv_udp_init().
2944
2945bufs -- List of buffers to send.
2946
2947nbufs -- Number of buffers in bufs.
2948
2949addr -- struct sockaddr_in or struct sockaddr_in6  with
2950                       the address and port of the remote peer.
2951
2952send_cb  --  Callback  to invoke when the data has been
2953                       sent out.
2954
2955              Returns
2956                     0 on success, or an error code < 0 on failure.
2957
2958              Changed in version 1.19.0: added 0.0.0.0  and  ::  to  localhost
2959              mapping
2960
2961
2962              Changed in version 1.27.0: added support for connected sockets
2963
2964
2965       int  uv_udp_try_send(uv_udp_t  *handle, const uv_buf_t bufs[], unsigned
2966       int nbufs, const struct sockaddr *addr)
2967              Same as uv_udp_send(), but won't queue  a  send  request  if  it
2968              can't be completed immediately.
2969
2970              For  connected  UDP handles, addr must be set to NULL, otherwise
2971              it will return UV_EISCONN error.
2972
2973              For connectionless UDP handles, addr cannot be  NULL,  otherwise
2974              it will return UV_EDESTADDRREQ error.
2975
2976              Returns
2977                     >=  0:  number of bytes sent (it matches the given buffer
2978                     size).  < 0: negative error code (UV_EAGAIN  is  returned
2979                     when the message can't be sent immediately).
2980
2981              Changed in version 1.27.0: added support for connected sockets
2982
2983
2984       int    uv_udp_recv_start(uv_udp_t    *handle,   uv_alloc_cb   alloc_cb,
2985       uv_udp_recv_cb recv_cb)
2986              Prepare for receiving data. If the  socket  has  not  previously
2987              been  bound  with uv_udp_bind() it is bound to 0.0.0.0 (the "all
2988              interfaces" IPv4 address) and a random port number.
2989
2990              Parameters
2991
2992handle -- UDP handle. Should have been initialized with
2993                       uv_udp_init().
2994
2995alloc_cb  --  Callback to invoke when temporary storage
2996                       is needed.
2997
2998recv_cb -- Callback to invoke with received data.
2999
3000              Returns
3001                     0 on success, or an error code < 0 on failure.
3002
3003              NOTE:
3004                 When using recvmmsg(2), the number of messages received at  a
3005                 time  is  limited  by the number of max size dgrams that will
3006                 fit into the buffer allocated in alloc_cb, and suggested_size
3007                 in  alloc_cb  for udp_recv is always set to the size of 1 max
3008                 size dgram.
3009
3010              Changed in version 1.35.0: added support for recvmmsg(2) on sup‐
3011              ported  platforms).   The  use of this feature requires a buffer
3012              larger than 2 * 64KB to be passed to alloc_cb.
3013
3014
3015              Changed in version 1.37.0: recvmmsg(2) support is no longer  en‐
3016              abled implicitly, it must be explicitly requested by passing the
3017              UV_UDP_RECVMMSG flag to uv_udp_init_ex().
3018
3019
3020              Changed in version 1.39.0: uv_udp_using_recvmmsg() can  be  used
3021              in  alloc_cb  to  determine  if  a  buffer  sized  for  use with
3022              recvmmsg(2) should be allocated for the current handle/platform.
3023
3024
3025       int uv_udp_using_recvmmsg(uv_udp_t *handle)
3026              Returns 1 if the UDP handle was created with the UV_UDP_RECVMMSG
3027              flag and the platform supports recvmmsg(2), 0 otherwise.
3028
3029              New in version 1.39.0.
3030
3031
3032       int uv_udp_recv_stop(uv_udp_t *handle)
3033              Stop listening for incoming datagrams.
3034
3035              Parameters
3036
3037handle -- UDP handle. Should have been initialized with
3038                       uv_udp_init().
3039
3040              Returns
3041                     0 on success, or an error code < 0 on failure.
3042
3043       size_t uv_udp_get_send_queue_size(const uv_udp_t *handle)
3044              Returns handle->send_queue_size.
3045
3046              New in version 1.19.0.
3047
3048
3049       size_t uv_udp_get_send_queue_count(const uv_udp_t *handle)
3050              Returns handle->send_queue_count.
3051
3052              New in version 1.19.0.
3053
3054
3055       SEE ALSO:
3056          The uv_handle_t API functions also apply.
3057
3058   uv_fs_event_t --- FS Event handle
3059       FS Event handles allow the user to monitor a given  path  for  changes,
3060       for  example,  if the file was renamed or there was a generic change in
3061       it. This handle uses the best backend for the job on each platform.
3062
3063       NOTE:
3064          For AIX, the non default IBM bos.ahafs package has to be  installed.
3065          The  AIX  Event  Infrastructure file system (ahafs) has some limita‐
3066          tions:
3067
3068              • ahafs tracks monitoring per process and is not thread safe.  A
3069                separate process must be spawned for each monitor for the same
3070                event.
3071
3072              • Events for file modification (writing to a file) are  not  re‐
3073                ceived if only the containing folder is watched.
3074
3075          See documentation for more details.
3076
3077          The  z/OS  file system events monitoring infrastructure does not no‐
3078          tify of file creation/deletion within a directory that is being mon‐
3079          itored.  See the IBM Knowledge centre for more details.
3080
3081   Data types
3082       type uv_fs_event_t
3083              FS Event handle type.
3084
3085       typedef void (*uv_fs_event_cb)(uv_fs_event_t *handle, const char *file‐
3086       name, int events, int status)
3087              Callback passed to uv_fs_event_start() which will be called  re‐
3088              peatedly after the handle is started.
3089
3090              If  the handle was started with a directory the filename parame‐
3091              ter will be a relative path to a file contained  in  the  direc‐
3092              tory, or NULL if the file name cannot be determined.
3093
3094              The events parameter is an ORed mask of uv_fs_event elements.
3095
3096       type uv_fs_event
3097              Event types that uv_fs_event_t handles monitor.
3098
3099                 enum uv_fs_event {
3100                     UV_RENAME = 1,
3101                     UV_CHANGE = 2
3102                 };
3103
3104       type uv_fs_event_flags
3105              Flags  that  can be passed to uv_fs_event_start() to control its
3106              behavior.
3107
3108                 enum uv_fs_event_flags {
3109                     /*
3110                     * By default, if the fs event watcher is given a directory name, we will
3111                     * watch for all events in that directory. This flags overrides this behavior
3112                     * and makes fs_event report only changes to the directory entry itself. This
3113                     * flag does not affect individual files watched.
3114                     * This flag is currently not implemented yet on any backend.
3115                     */
3116                     UV_FS_EVENT_WATCH_ENTRY = 1,
3117                     /*
3118                     * By default uv_fs_event will try to use a kernel interface such as inotify
3119                     * or kqueue to detect events. This may not work on remote file systems such
3120                     * as NFS mounts. This flag makes fs_event fall back to calling stat() on a
3121                     * regular interval.
3122                     * This flag is currently not implemented yet on any backend.
3123                     */
3124                     UV_FS_EVENT_STAT = 2,
3125                     /*
3126                     * By default, event watcher, when watching directory, is not registering
3127                     * (is ignoring) changes in its subdirectories.
3128                     * This flag will override this behaviour on platforms that support it.
3129                     */
3130                     UV_FS_EVENT_RECURSIVE = 4
3131                 };
3132
3133   Public members
3134       N/A
3135
3136       SEE ALSO:
3137          The uv_handle_t members also apply.
3138
3139   API
3140       int uv_fs_event_init(uv_loop_t *loop, uv_fs_event_t *handle)
3141              Initialize the handle.
3142
3143       int uv_fs_event_start(uv_fs_event_t *handle, uv_fs_event_cb  cb,  const
3144       char *path, unsigned int flags)
3145              Start  the  handle with the given callback, which will watch the
3146              specified path for  changes.  flags  can  be  an  ORed  mask  of
3147              uv_fs_event_flags.
3148
3149              NOTE:
3150                 Currently  the  only  supported flag is UV_FS_EVENT_RECURSIVE
3151                 and only on OSX and Windows.
3152
3153       int uv_fs_event_stop(uv_fs_event_t *handle)
3154              Stop the handle, the callback will no longer be called.
3155
3156       int uv_fs_event_getpath(uv_fs_event_t  *handle,  char  *buffer,  size_t
3157       *size)
3158              Get  the  path being monitored by the handle. The buffer must be
3159              preallocated by the user. Returns 0 on success or an error  code
3160              <  0  in  case  of failure.  On success, buffer will contain the
3161              path and size its length.  If  the  buffer  is  not  big  enough
3162              UV_ENOBUFS will be returned and size will be set to the required
3163              size, including the null terminator.
3164
3165              Changed in version 1.3.0: the returned length no longer includes
3166              the  terminating  null  byte,  and the buffer is not null termi‐
3167              nated.
3168
3169
3170              Changed in version 1.9.0: the returned length includes the  ter‐
3171              minating  null byte on UV_ENOBUFS, and the buffer is null termi‐
3172              nated on success.
3173
3174
3175       SEE ALSO:
3176          The uv_handle_t API functions also apply.
3177
3178   uv_fs_poll_t --- FS Poll handle
3179       FS Poll handles allow the user to monitor a given path for changes. Un‐
3180       like  uv_fs_event_t, fs poll handles use stat to detect when a file has
3181       changed so they can work on file systems where fs event handles can't.
3182
3183   Data types
3184       type uv_fs_poll_t
3185              FS Poll handle type.
3186
3187       typedef void (*uv_fs_poll_cb)(uv_fs_poll_t *handle, int  status,  const
3188       uv_stat_t *prev, const uv_stat_t *curr)
3189              Callback  passed  to uv_fs_poll_start() which will be called re‐
3190              peatedly after the handle is started, when any change happens to
3191              the monitored path.
3192
3193              The  callback  is invoked with status < 0 if path does not exist
3194              or is inaccessible. The watcher is not stopped but your callback
3195              is  not called again until something changes (e.g. when the file
3196              is created or the error reason changes).
3197
3198              When status == 0, the callback receives pointers to the old  and
3199              new  uv_stat_t  structs.  They are valid for the duration of the
3200              callback only.
3201
3202   Public members
3203       N/A
3204
3205       SEE ALSO:
3206          The uv_handle_t members also apply.
3207
3208   API
3209       int uv_fs_poll_init(uv_loop_t *loop, uv_fs_poll_t *handle)
3210              Initialize the handle.
3211
3212       int uv_fs_poll_start(uv_fs_poll_t *handle, uv_fs_poll_cb poll_cb, const
3213       char *path, unsigned int interval)
3214              Check the file at path for changes every interval milliseconds.
3215
3216              NOTE:
3217                 For maximum portability, use multi-second intervals. Sub-sec‐
3218                 ond intervals will not detect all changes on many  file  sys‐
3219                 tems.
3220
3221       int uv_fs_poll_stop(uv_fs_poll_t *handle)
3222              Stop the handle, the callback will no longer be called.
3223
3224       int   uv_fs_poll_getpath(uv_fs_poll_t  *handle,  char  *buffer,  size_t
3225       *size)
3226              Get the path being monitored by the handle. The buffer  must  be
3227              preallocated  by the user. Returns 0 on success or an error code
3228              < 0 in case of failure.  On success,  buffer  will  contain  the
3229              path  and  size  its  length.  If  the  buffer is not big enough
3230              UV_ENOBUFS will be returned and size will be set to the required
3231              size.
3232
3233              Changed in version 1.3.0: the returned length no longer includes
3234              the terminating null byte, and the buffer  is  not  null  termi‐
3235              nated.
3236
3237
3238              Changed  in version 1.9.0: the returned length includes the ter‐
3239              minating null byte on UV_ENOBUFS, and the buffer is null  termi‐
3240              nated on success.
3241
3242
3243       SEE ALSO:
3244          The uv_handle_t API functions also apply.
3245
3246   File system operations
3247       libuv  provides  a  wide  variety of cross-platform sync and async file
3248       system operations. All functions defined in this document take a  call‐
3249       back,  which is allowed to be NULL. If the callback is NULL the request
3250       is completed  synchronously,  otherwise  it  will  be  performed  asyn‐
3251       chronously.
3252
3253       All  file  operations  are  run on the threadpool. See Thread pool work
3254       scheduling for information on the threadpool size.
3255
3256       Starting with libuv v1.45.0, some file operations on Linux  are  handed
3257       off to io_uring <https://en.wikipedia.org/wiki/Io_uring> when possible.
3258       Apart from a  (sometimes  significant)  increase  in  throughput  there
3259       should  be no change in observable behavior. Libuv reverts to using its
3260       threadpool when the necessary kernel features are  unavailable  or  un‐
3261       suitable.
3262
3263       NOTE:
3264          On Windows uv_fs_* functions use utf-8 encoding.
3265
3266   Data types
3267       type uv_fs_t
3268              File system request type.
3269
3270       type uv_timespec_t
3271              Y2K38-unsafe data type for storing times with nanosecond resolu‐
3272              tion.  Will be replaced with uv_timespec64_t in libuv v2.0.
3273
3274                 typedef struct {
3275                     long tv_sec;
3276                     long tv_nsec;
3277                 } uv_timespec_t;
3278
3279       type uv_stat_t
3280              Portable equivalent of struct stat.
3281
3282                 typedef struct {
3283                     uint64_t st_dev;
3284                     uint64_t st_mode;
3285                     uint64_t st_nlink;
3286                     uint64_t st_uid;
3287                     uint64_t st_gid;
3288                     uint64_t st_rdev;
3289                     uint64_t st_ino;
3290                     uint64_t st_size;
3291                     uint64_t st_blksize;
3292                     uint64_t st_blocks;
3293                     uint64_t st_flags;
3294                     uint64_t st_gen;
3295                     uv_timespec_t st_atim;
3296                     uv_timespec_t st_mtim;
3297                     uv_timespec_t st_ctim;
3298                     uv_timespec_t st_birthtim;
3299                 } uv_stat_t;
3300
3301       enum uv_fs_type
3302              File system request type.
3303
3304                 typedef enum {
3305                     UV_FS_UNKNOWN = -1,
3306                     UV_FS_CUSTOM,
3307                     UV_FS_OPEN,
3308                     UV_FS_CLOSE,
3309                     UV_FS_READ,
3310                     UV_FS_WRITE,
3311                     UV_FS_SENDFILE,
3312                     UV_FS_STAT,
3313                     UV_FS_LSTAT,
3314                     UV_FS_FSTAT,
3315                     UV_FS_FTRUNCATE,
3316                     UV_FS_UTIME,
3317                     UV_FS_FUTIME,
3318                     UV_FS_ACCESS,
3319                     UV_FS_CHMOD,
3320                     UV_FS_FCHMOD,
3321                     UV_FS_FSYNC,
3322                     UV_FS_FDATASYNC,
3323                     UV_FS_UNLINK,
3324                     UV_FS_RMDIR,
3325                     UV_FS_MKDIR,
3326                     UV_FS_MKDTEMP,
3327                     UV_FS_RENAME,
3328                     UV_FS_SCANDIR,
3329                     UV_FS_LINK,
3330                     UV_FS_SYMLINK,
3331                     UV_FS_READLINK,
3332                     UV_FS_CHOWN,
3333                     UV_FS_FCHOWN,
3334                     UV_FS_REALPATH,
3335                     UV_FS_COPYFILE,
3336                     UV_FS_LCHOWN,
3337                     UV_FS_OPENDIR,
3338                     UV_FS_READDIR,
3339                     UV_FS_CLOSEDIR,
3340                     UV_FS_MKSTEMP,
3341                     UV_FS_LUTIME
3342                 } uv_fs_type;
3343
3344       type uv_statfs_t
3345              Reduced cross platform equivalent of  struct  statfs.   Used  in
3346              uv_fs_statfs().
3347
3348                 typedef struct uv_statfs_s {
3349                     uint64_t f_type;
3350                     uint64_t f_bsize;
3351                     uint64_t f_blocks;
3352                     uint64_t f_bfree;
3353                     uint64_t f_bavail;
3354                     uint64_t f_files;
3355                     uint64_t f_ffree;
3356                     uint64_t f_spare[4];
3357                 } uv_statfs_t;
3358
3359       enum uv_dirent_t
3360              Cross  platform  (reduced) equivalent of struct dirent.  Used in
3361              uv_fs_scandir_next().
3362
3363                 typedef enum {
3364                     UV_DIRENT_UNKNOWN,
3365                     UV_DIRENT_FILE,
3366                     UV_DIRENT_DIR,
3367                     UV_DIRENT_LINK,
3368                     UV_DIRENT_FIFO,
3369                     UV_DIRENT_SOCKET,
3370                     UV_DIRENT_CHAR,
3371                     UV_DIRENT_BLOCK
3372                 } uv_dirent_type_t;
3373
3374                 typedef struct uv_dirent_s {
3375                     const char* name;
3376                     uv_dirent_type_t type;
3377                 } uv_dirent_t;
3378
3379       type uv_dir_t
3380              Data type used  for  streaming  directory  iteration.   Used  by
3381              uv_fs_opendir(),  uv_fs_readdir(), and uv_fs_closedir(). dirents
3382              represents a user provided array of uv_dirent_t`s used  to  hold
3383              results.  `nentries  is  the user provided maximum array size of
3384              dirents.
3385
3386                 typedef struct uv_dir_s {
3387                     uv_dirent_t* dirents;
3388                     size_t nentries;
3389                 } uv_dir_t;
3390
3391       typedef void (*uv_fs_cb)(uv_fs_t *req)
3392              Callback called when a request is completed asynchronously.
3393
3394   Public members
3395       uv_loop_t *uv_fs_t.loop
3396              Loop that started this request and where completion will be  re‐
3397              ported.  Readonly.
3398
3399       uv_fs_type uv_fs_t.fs_type
3400              FS request type.
3401
3402       const char *uv_fs_t.path
3403              Path affecting the request.
3404
3405       ssize_t uv_fs_t.result
3406              Result  of  the  request. < 0 means error, success otherwise. On
3407              requests such as uv_fs_read() or uv_fs_write() it indicates  the
3408              amount of data that was read or written, respectively.
3409
3410       uv_stat_t uv_fs_t.statbuf
3411              Stores the result of uv_fs_stat() and other stat requests.
3412
3413       void *uv_fs_t.ptr
3414              Stores  the  result of uv_fs_readlink() and uv_fs_realpath() and
3415              serves as an alias to statbuf.
3416
3417       SEE ALSO:
3418          The uv_req_t members also apply.
3419
3420   API
3421       void uv_fs_req_cleanup(uv_fs_t *req)
3422              Cleanup request. Must be called after a request is  finished  to
3423              deallocate any memory libuv might have allocated.
3424
3425       int  uv_fs_close(uv_loop_t  *loop, uv_fs_t *req, uv_file file, uv_fs_cb
3426       cb)
3427              Equivalent to close(2).
3428
3429       int uv_fs_open(uv_loop_t *loop, uv_fs_t *req,  const  char  *path,  int
3430       flags, int mode, uv_fs_cb cb)
3431              Equivalent to open(2).
3432
3433              NOTE:
3434                 On Windows libuv uses CreateFileW and thus the file is always
3435                 opened in binary mode.  Because  of  this  the  O_BINARY  and
3436                 O_TEXT flags are not supported.
3437
3438       int  uv_fs_read(uv_loop_t  *loop,  uv_fs_t  *req,  uv_file  file, const
3439       uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)
3440              Equivalent to preadv(2). If the offset argument is -1, then  the
3441              current file offset is used and updated.
3442
3443              WARNING:
3444                 On  Windows,  under  non-MSVC  environments (e.g. when GCC or
3445                 Clang  is  used  to  build   libuv),   files   opened   using
3446                 UV_FS_O_FILEMAP  may cause a fatal crash if the memory mapped
3447                 read operation fails.
3448
3449       int uv_fs_unlink(uv_loop_t  *loop,  uv_fs_t  *req,  const  char  *path,
3450       uv_fs_cb cb)
3451              Equivalent to unlink(2).
3452
3453       int  uv_fs_write(uv_loop_t  *loop,  uv_fs_t  *req,  uv_file file, const
3454       uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)
3455              Equivalent to pwritev(2). If the offset argument is -1, then the
3456              current file offset is used and updated.
3457
3458              WARNING:
3459                 On  Windows,  under  non-MSVC  environments (e.g. when GCC or
3460                 Clang  is  used  to  build   libuv),   files   opened   using
3461                 UV_FS_O_FILEMAP  may cause a fatal crash if the memory mapped
3462                 write operation fails.
3463
3464       int uv_fs_mkdir(uv_loop_t *loop, uv_fs_t *req, const  char  *path,  int
3465       mode, uv_fs_cb cb)
3466              Equivalent to mkdir(2).
3467
3468              NOTE:
3469                 mode is currently not implemented on Windows.
3470
3471       int  uv_fs_mkdtemp(uv_loop_t  *loop,  uv_fs_t  *req,  const  char *tpl,
3472       uv_fs_cb cb)
3473              Equivalent to mkdtemp(3). The result can be found as a null ter‐
3474              minated string at req->path.
3475
3476       int  uv_fs_mkstemp(uv_loop_t  *loop,  uv_fs_t  *req,  const  char *tpl,
3477       uv_fs_cb cb)
3478              Equivalent to mkstemp(3). The created file path can be found  as
3479              a  null terminated string at req->path.  The file descriptor can
3480              be found as an integer at req->result.
3481
3482              New in version 1.34.0.
3483
3484
3485       int  uv_fs_rmdir(uv_loop_t  *loop,  uv_fs_t  *req,  const  char  *path,
3486       uv_fs_cb cb)
3487              Equivalent to rmdir(2).
3488
3489       int  uv_fs_opendir(uv_loop_t  *loop,  uv_fs_t  *req,  const char *path,
3490       uv_fs_cb cb)
3491              Opens path as a directory stream. On success, a uv_dir_t is  al‐
3492              located  and  returned via req->ptr. This memory is not freed by
3493              uv_fs_req_cleanup(), although req->ptr is set to NULL. The allo‐
3494              cated memory must be freed by calling uv_fs_closedir(). On fail‐
3495              ure, no memory is allocated.
3496
3497              The contents of the directory can be iterated  over  by  passing
3498              the resulting uv_dir_t to uv_fs_readdir().
3499
3500              New in version 1.28.0.
3501
3502
3503       int   uv_fs_closedir(uv_loop_t  *loop,  uv_fs_t  *req,  uv_dir_t  *dir,
3504       uv_fs_cb cb)
3505              Closes the directory stream represented by  dir  and  frees  the
3506              memory allocated by uv_fs_opendir().
3507
3508              New in version 1.28.0.
3509
3510
3511       int   uv_fs_readdir(uv_loop_t   *loop,  uv_fs_t  *req,  uv_dir_t  *dir,
3512       uv_fs_cb cb)
3513              Iterates over the directory stream, dir, returned by a  success‐
3514              ful uv_fs_opendir() call. Prior to invoking uv_fs_readdir(), the
3515              caller must set dir->dirents and dir->nentries, representing the
3516              array  of  uv_dirent_t  elements used to hold the read directory
3517              entries and its size.
3518
3519              On success, the result is an integer >= 0 representing the  num‐
3520              ber of entries read from the stream.
3521
3522              New in version 1.28.0.
3523
3524
3525              WARNING:
3526                 uv_fs_readdir() is not thread safe.
3527
3528              NOTE:
3529                 This function does not return the "." and ".." entries.
3530
3531              NOTE:
3532                 On  success this function allocates memory that must be freed
3533                 using uv_fs_req_cleanup(). uv_fs_req_cleanup() must be called
3534                 before closing the directory with uv_fs_closedir().
3535
3536       int  uv_fs_scandir(uv_loop_t *loop, uv_fs_t *req, const char *path, int
3537       flags, uv_fs_cb cb)
3538
3539       int uv_fs_scandir_next(uv_fs_t *req, uv_dirent_t *ent)
3540              Equivalent to scandir(3), with a slightly  different  API.  Once
3541              the  callback  for  the  request  is  called,  the  user can use
3542              uv_fs_scandir_next() to get ent populated with the  next  direc‐
3543              tory  entry  data. When there are no more entries UV_EOF will be
3544              returned.
3545
3546              NOTE:
3547                 Unlike scandir(3), this function does not return the "."  and
3548                 ".." entries.
3549
3550              NOTE:
3551                 On  Linux,  getting the type of an entry is only supported by
3552                 some file systems (btrfs, ext2, ext3 and ext4 at the time  of
3553                 this writing), check the getdents(2) man page.
3554
3555       int   uv_fs_stat(uv_loop_t  *loop,  uv_fs_t  *req,  const  char  *path,
3556       uv_fs_cb cb)
3557
3558       int uv_fs_fstat(uv_loop_t *loop, uv_fs_t *req, uv_file  file,  uv_fs_cb
3559       cb)
3560
3561       int  uv_fs_lstat(uv_loop_t  *loop,  uv_fs_t  *req,  const  char  *path,
3562       uv_fs_cb cb)
3563              Equivalent to stat(2), fstat(2) and lstat(2) respectively.
3564
3565       int uv_fs_statfs(uv_loop_t  *loop,  uv_fs_t  *req,  const  char  *path,
3566       uv_fs_cb cb)
3567              Equivalent  to statfs(2). On success, a uv_statfs_t is allocated
3568              and  returned  via   req->ptr.   This   memory   is   freed   by
3569              uv_fs_req_cleanup().
3570
3571              NOTE:
3572                 Any  fields  in  the  resulting uv_statfs_t that are not sup‐
3573                 ported by the underlying operating system are set to zero.
3574
3575              New in version 1.31.0.
3576
3577
3578       int uv_fs_rename(uv_loop_t *loop, uv_fs_t *req, const char *path, const
3579       char *new_path, uv_fs_cb cb)
3580              Equivalent to rename(2).
3581
3582       int  uv_fs_fsync(uv_loop_t  *loop, uv_fs_t *req, uv_file file, uv_fs_cb
3583       cb)
3584              Equivalent to fsync(2).
3585
3586              NOTE:
3587                 For AIX, uv_fs_fsync returns  UV_EBADF  on  file  descriptors
3588                 referencing non regular files.
3589
3590       int   uv_fs_fdatasync(uv_loop_t  *loop,  uv_fs_t  *req,  uv_file  file,
3591       uv_fs_cb cb)
3592              Equivalent to fdatasync(2).
3593
3594       int  uv_fs_ftruncate(uv_loop_t  *loop,  uv_fs_t  *req,  uv_file   file,
3595       int64_t offset, uv_fs_cb cb)
3596              Equivalent to ftruncate(2).
3597
3598       int  uv_fs_copyfile(uv_loop_t  *loop,  uv_fs_t  *req, const char *path,
3599       const char *new_path, int flags, uv_fs_cb cb)
3600              Copies a file from path to new_path.  Supported  flags  are  de‐
3601              scribed below.
3602
3603UV_FS_COPYFILE_EXCL:  If  present,  uv_fs_copyfile() will fail
3604                with UV_EEXIST if the destination path already exists. The de‐
3605                fault behavior is to overwrite the destination if it exists.
3606
3607UV_FS_COPYFILE_FICLONE:  If present, uv_fs_copyfile() will at‐
3608                tempt to create a copy-on-write  reflink.  If  the  underlying
3609                platform  does  not  support copy-on-write, or an error occurs
3610                while attempting to use copy-on-write, a fallback copy  mecha‐
3611                nism based on uv_fs_sendfile() is used.
3612
3613UV_FS_COPYFILE_FICLONE_FORCE:   If  present,  uv_fs_copyfile()
3614                will attempt to create a copy-on-write reflink. If the  under‐
3615                lying platform does not support copy-on-write, or an error oc‐
3616                curs while attempting to use copy-on-write, then an  error  is
3617                returned.
3618
3619              WARNING:
3620                 If the destination path is created, but an error occurs while
3621                 copying the data, then the destination path is removed. There
3622                 is  a  brief  window of time between closing and removing the
3623                 file where another process could access the file.
3624
3625              New in version 1.14.0.
3626
3627
3628              Changed   in   version   1.20.0:   UV_FS_COPYFILE_FICLONE    and
3629              UV_FS_COPYFILE_FICLONE_FORCE are supported.
3630
3631
3632              Changed  in  version  1.33.0:  If  an  error  occurs while using
3633              UV_FS_COPYFILE_FICLONE_FORCE, that  error  is  returned.  Previ‐
3634              ously, all errors were mapped to UV_ENOTSUP.
3635
3636
3637       int  uv_fs_sendfile(uv_loop_t  *loop,  uv_fs_t  *req,  uv_file  out_fd,
3638       uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb)
3639              Limited equivalent to sendfile(2).
3640
3641       int uv_fs_access(uv_loop_t *loop, uv_fs_t *req, const char  *path,  int
3642       mode, uv_fs_cb cb)
3643              Equivalent   to  access(2)  on  Unix.  Windows  uses  GetFileAt‐
3644              tributesW().
3645
3646       int uv_fs_chmod(uv_loop_t *loop, uv_fs_t *req, const  char  *path,  int
3647       mode, uv_fs_cb cb)
3648
3649       int uv_fs_fchmod(uv_loop_t *loop, uv_fs_t *req, uv_file file, int mode,
3650       uv_fs_cb cb)
3651              Equivalent to chmod(2) and fchmod(2) respectively.
3652
3653       int uv_fs_utime(uv_loop_t *loop, uv_fs_t *req, const char *path, double
3654       atime, double mtime, uv_fs_cb cb)
3655
3656       int  uv_fs_futime(uv_loop_t  *loop,  uv_fs_t *req, uv_file file, double
3657       atime, double mtime, uv_fs_cb cb)
3658
3659       int uv_fs_lutime(uv_loop_t *loop, uv_fs_t *req, const char *path,  dou‐
3660       ble atime, double mtime, uv_fs_cb cb)
3661              Equivalent to utime(2), futimes(3) and lutimes(3) respectively.
3662
3663              NOTE:
3664                 z/OS:  uv_fs_lutime()  is  not  implemented  for z/OS. It can
3665                 still be called but will return UV_ENOSYS.
3666
3667              NOTE:
3668                 AIX: uv_fs_futime() and uv_fs_lutime()  functions  only  work
3669                 for  AIX  7.1  and  newer.  They can still be called on older
3670                 versions but will return UV_ENOSYS.
3671
3672              Changed in version 1.10.0: sub-second precission is supported on
3673              Windows
3674
3675
3676       int  uv_fs_link(uv_loop_t  *loop, uv_fs_t *req, const char *path, const
3677       char *new_path, uv_fs_cb cb)
3678              Equivalent to link(2).
3679
3680       int uv_fs_symlink(uv_loop_t *loop,  uv_fs_t  *req,  const  char  *path,
3681       const char *new_path, int flags, uv_fs_cb cb)
3682              Equivalent to symlink(2).
3683
3684              NOTE:
3685                 On  Windows  the  flags parameter can be specified to control
3686                 how the symlink will be created:
3687
3688UV_FS_SYMLINK_DIR: indicates that path points to a  di‐
3689                       rectory.
3690
3691UV_FS_SYMLINK_JUNCTION:  request  that  the  symlink is
3692                       created using junction points.
3693
3694       int uv_fs_readlink(uv_loop_t *loop, uv_fs_t  *req,  const  char  *path,
3695       uv_fs_cb cb)
3696              Equivalent  to  readlink(2).   The resulting string is stored in
3697              req->ptr.
3698
3699       int uv_fs_realpath(uv_loop_t *loop, uv_fs_t  *req,  const  char  *path,
3700       uv_fs_cb cb)
3701              Equivalent    to    realpath(3)    on    Unix.    Windows   uses
3702              GetFinalPathNameByHandle.  The resulting  string  is  stored  in
3703              req->ptr.
3704
3705              WARNING:
3706                 This function has certain platform-specific caveats that were
3707                 discovered when used in Node.
3708
3709                 • macOS and other BSDs: this function will fail with UV_ELOOP
3710                   if  more  than  32  symlinks  are found while resolving the
3711                   given  path.   This  limit  is  hardcoded  and  cannot   be
3712                   sidestepped.
3713
3714                 • Windows:  while  this  function  works  in the common case,
3715                   there are a number of corner cases where it doesn't:
3716
3717                   • Paths in ramdisk volumes created by tools which  sidestep
3718                     the Volume Manager (such as ImDisk) cannot be resolved.
3719
3720                   • Inconsistent casing when using drive letters.
3721
3722                   • Resolved path bypasses subst'd drives.
3723
3724                 While  this  function can still be used, it's not recommended
3725                 if scenarios such as the above need to be supported.
3726
3727                 The background story and some more details  on  these  issues
3728                 can be checked here.
3729
3730              New in version 1.8.0.
3731
3732
3733       int  uv_fs_chown(uv_loop_t  *loop,  uv_fs_t  *req,  const  char  *path,
3734       uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb)
3735
3736       int uv_fs_fchown(uv_loop_t *loop, uv_fs_t *req, uv_file file,  uv_uid_t
3737       uid, uv_gid_t gid, uv_fs_cb cb)
3738
3739       int  uv_fs_lchown(uv_loop_t  *loop,  uv_fs_t  *req,  const  char *path,
3740       uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb)
3741              Equivalent to chown(2), fchown(2) and lchown(2) respectively.
3742
3743              NOTE:
3744                 These functions are not implemented on Windows.
3745
3746              Changed in version 1.21.0: implemented uv_fs_lchown
3747
3748
3749       uv_fs_type uv_fs_get_type(const uv_fs_t *req)
3750              Returns req->fs_type.
3751
3752              New in version 1.19.0.
3753
3754
3755       ssize_t uv_fs_get_result(const uv_fs_t *req)
3756              Returns req->result.
3757
3758              New in version 1.19.0.
3759
3760
3761       int uv_fs_get_system_error(const uv_fs_t *req)
3762              Returns the platform specific error code - GetLastError()  value
3763              on Windows and -(req->result) on other platforms.
3764
3765              New in version 1.38.0.
3766
3767
3768       void *uv_fs_get_ptr(const uv_fs_t *req)
3769              Returns req->ptr.
3770
3771              New in version 1.19.0.
3772
3773
3774       const char *uv_fs_get_path(const uv_fs_t *req)
3775              Returns req->path.
3776
3777              New in version 1.19.0.
3778
3779
3780       uv_stat_t *uv_fs_get_statbuf(uv_fs_t *req)
3781              Returns &req->statbuf.
3782
3783              New in version 1.19.0.
3784
3785
3786       SEE ALSO:
3787          The uv_req_t API functions also apply.
3788
3789   Helper functions
3790       uv_os_fd_t uv_get_osfhandle(int fd)
3791              For  a  file  descriptor  in the C runtime, get the OS-dependent
3792              handle.  On UNIX, returns the fd intact. On Windows, this  calls
3793              _get_osfhandle.   Note  that  the return value is still owned by
3794              the C runtime, any attempts to close it or to use it after clos‐
3795              ing the fd may lead to malfunction.
3796                 New in version 1.12.0.
3797
3798
3799       int uv_open_osfhandle(uv_os_fd_t os_fd)
3800              For a OS-dependent handle, get the file descriptor in the C run‐
3801              time.  On UNIX, returns the os_fd intact. On Windows, this calls
3802              _open_osfhandle.   Note that this consumes the argument, any at‐
3803              tempts to close it or to use it after closing the  return  value
3804              may lead to malfunction.
3805                 New in version 1.23.0.
3806
3807
3808   File open constants
3809       UV_FS_O_APPEND
3810              The  file  is opened in append mode. Before each write, the file
3811              offset is positioned at the end of the file.
3812
3813       UV_FS_O_CREAT
3814              The file is created if it does not already exist.
3815
3816       UV_FS_O_DIRECT
3817              File I/O is done directly to and from user-space buffers,  which
3818              must be aligned. Buffer size and address should be a multiple of
3819              the physical sector size of the block device.
3820
3821              NOTE:
3822                 UV_FS_O_DIRECT is supported on  Linux,  and  on  Windows  via
3823                 FILE_FLAG_NO_BUFFERING.   UV_FS_O_DIRECT  is not supported on
3824                 macOS.
3825
3826       UV_FS_O_DIRECTORY
3827              If the path is not a directory, fail the open.
3828
3829              NOTE:
3830                 UV_FS_O_DIRECTORY is not supported on Windows.
3831
3832       UV_FS_O_DSYNC
3833              The file is opened for synchronous I/O.  Write  operations  will
3834              complete  once all data and a minimum of metadata are flushed to
3835              disk.
3836
3837              NOTE:
3838                 UV_FS_O_DSYNC     is     supported     on     Windows     via
3839                 FILE_FLAG_WRITE_THROUGH.
3840
3841       UV_FS_O_EXCL
3842              If the O_CREAT flag is set and the file already exists, fail the
3843              open.
3844
3845              NOTE:
3846                 In general, the behavior of O_EXCL is undefined if it is used
3847                 without  O_CREAT.  There  is  one exception: on Linux 2.6 and
3848                 later, O_EXCL can be used without O_CREAT if pathname  refers
3849                 to  a block device. If the block device is in use by the sys‐
3850                 tem (e.g., mounted), the open will fail with the error EBUSY.
3851
3852       UV_FS_O_EXLOCK
3853              Atomically obtain an exclusive lock.
3854
3855              NOTE:
3856                 UV_FS_O_EXLOCK is only supported on macOS and Windows.
3857
3858              Changed in version 1.17.0: support is added for Windows.
3859
3860
3861       UV_FS_O_FILEMAP
3862              Use a memory file mapping to access the file.  When  using  this
3863              flag, the file cannot be open multiple times concurrently.
3864
3865              NOTE:
3866                 UV_FS_O_FILEMAP is only supported on Windows.
3867
3868       UV_FS_O_NOATIME
3869              Do not update the file access time when the file is read.
3870
3871              NOTE:
3872                 UV_FS_O_NOATIME is not supported on Windows.
3873
3874       UV_FS_O_NOCTTY
3875              If  the path identifies a terminal device, opening the path will
3876              not cause that terminal to become the controlling  terminal  for
3877              the process (if the process does not already have one).
3878
3879              NOTE:
3880                 UV_FS_O_NOCTTY is not supported on Windows.
3881
3882       UV_FS_O_NOFOLLOW
3883              If the path is a symbolic link, fail the open.
3884
3885              NOTE:
3886                 UV_FS_O_NOFOLLOW is not supported on Windows.
3887
3888       UV_FS_O_NONBLOCK
3889              Open the file in nonblocking mode if possible.
3890
3891              NOTE:
3892                 UV_FS_O_NONBLOCK is not supported on Windows.
3893
3894       UV_FS_O_RANDOM
3895              Access  is  intended  to be random. The system can use this as a
3896              hint to optimize file caching.
3897
3898              NOTE:
3899                 UV_FS_O_RANDOM   is   only   supported   on    Windows    via
3900                 FILE_FLAG_RANDOM_ACCESS.
3901
3902       UV_FS_O_RDONLY
3903              Open the file for read-only access.
3904
3905       UV_FS_O_RDWR
3906              Open the file for read-write access.
3907
3908       UV_FS_O_SEQUENTIAL
3909              Access  is  intended to be sequential from beginning to end. The
3910              system can use this as a hint to optimize file caching.
3911
3912              NOTE:
3913                 UV_FS_O_SEQUENTIAL  is  only   supported   on   Windows   via
3914                 FILE_FLAG_SEQUENTIAL_SCAN.
3915
3916       UV_FS_O_SHORT_LIVED
3917              The  file is temporary and should not be flushed to disk if pos‐
3918              sible.
3919
3920              NOTE:
3921                 UV_FS_O_SHORT_LIVED  is  only  supported   on   Windows   via
3922                 FILE_ATTRIBUTE_TEMPORARY.
3923
3924       UV_FS_O_SYMLINK
3925              Open the symbolic link itself rather than the resource it points
3926              to.
3927
3928       UV_FS_O_SYNC
3929              The file is opened for synchronous I/O.  Write  operations  will
3930              complete once all data and all metadata are flushed to disk.
3931
3932              NOTE:
3933                 UV_FS_O_SYNC      is     supported     on     Windows     via
3934                 FILE_FLAG_WRITE_THROUGH.
3935
3936       UV_FS_O_TEMPORARY
3937              The file is temporary and should not be flushed to disk if  pos‐
3938              sible.
3939
3940              NOTE:
3941                 UV_FS_O_TEMPORARY   is   only   supported   on   Windows  via
3942                 FILE_ATTRIBUTE_TEMPORARY.
3943
3944       UV_FS_O_TRUNC
3945              If the file exists and is a regular file, and the file is opened
3946              successfully  for write access, its length shall be truncated to
3947              zero.
3948
3949       UV_FS_O_WRONLY
3950              Open the file for write-only access.
3951
3952   Thread pool work scheduling
3953       libuv provides a threadpool which can be used to run user code and  get
3954       notified in the loop thread. This thread pool is internally used to run
3955       all file system operations, as well as getaddrinfo and getnameinfo  re‐
3956       quests.
3957
3958       Its default size is 4, but it can be changed at startup time by setting
3959       the UV_THREADPOOL_SIZE environment variable to any value (the  absolute
3960       maximum is 1024).
3961
3962       Changed  in  version 1.30.0: the maximum UV_THREADPOOL_SIZE allowed was
3963       increased from 128 to 1024.
3964
3965
3966       Changed in version 1.45.0: threads now have an 8 MB  stack  instead  of
3967       the (sometimes too low) platform default.
3968
3969
3970       The threadpool is global and shared across all event loops. When a par‐
3971       ticular  function  makes  use  of  the  threadpool  (i.e.  when   using
3972       uv_queue_work())  libuv preallocates and initializes the maximum number
3973       of threads allowed by UV_THREADPOOL_SIZE. This causes a relatively  mi‐
3974       nor  memory  overhead  (~1MB for 128 threads) but increases the perfor‐
3975       mance of threading at runtime.
3976
3977       NOTE:
3978          Note that even though a global thread pool which  is  shared  across
3979          all events loops is used, the functions are not thread safe.
3980
3981   Data types
3982       type uv_work_t
3983              Work request type.
3984
3985       typedef void (*uv_work_cb)(uv_work_t *req)
3986              Callback  passed  to  uv_queue_work()  which  will be run on the
3987              thread pool.
3988
3989       typedef void (*uv_after_work_cb)(uv_work_t *req, int status)
3990              Callback passed to uv_queue_work() which will be called  on  the
3991              loop thread after the work on the threadpool has been completed.
3992              If the work was  cancelled  using  uv_cancel()  status  will  be
3993              UV_ECANCELED.
3994
3995   Public members
3996       uv_loop_t *uv_work_t.loop
3997              Loop  that started this request and where completion will be re‐
3998              ported.  Readonly.
3999
4000       SEE ALSO:
4001          The uv_req_t members also apply.
4002
4003   API
4004       int uv_queue_work(uv_loop_t *loop, uv_work_t *req, uv_work_cb  work_cb,
4005       uv_after_work_cb after_work_cb)
4006              Initializes a work request which will run the given work_cb in a
4007              thread from the  threadpool.  Once  work_cb  is  completed,  af‐
4008              ter_work_cb will be called on the loop thread.
4009
4010              This request can be cancelled with uv_cancel().
4011
4012       SEE ALSO:
4013          The uv_req_t API functions also apply.
4014
4015   DNS utility functions
4016       libuv provides asynchronous variants of getaddrinfo and getnameinfo.
4017
4018   Data types
4019       type uv_getaddrinfo_t
4020              getaddrinfo request type.
4021
4022       typedef  void  (*uv_getaddrinfo_cb)(uv_getaddrinfo_t  *req, int status,
4023       struct addrinfo *res)
4024              Callback which will be called with the getaddrinfo  request  re‐
4025              sult once complete. In case it was cancelled, status will have a
4026              value of UV_ECANCELED.
4027
4028       type uv_getnameinfo_t
4029              getnameinfo request type.
4030
4031       typedef void (*uv_getnameinfo_cb)(uv_getnameinfo_t  *req,  int  status,
4032       const char *hostname, const char *service)
4033              Callback  which  will be called with the getnameinfo request re‐
4034              sult once complete. In case it was cancelled, status will have a
4035              value of UV_ECANCELED.
4036
4037   Public members
4038       uv_loop_t *uv_getaddrinfo_t.loop
4039              Loop  that started this getaddrinfo request and where completion
4040              will be reported. Readonly.
4041
4042       struct addrinfo *uv_getaddrinfo_t.addrinfo
4043              Pointer to a struct addrinfo  containing  the  result.  Must  be
4044              freed by the user with uv_freeaddrinfo().
4045
4046              Changed in version 1.3.0: the field is declared as public.
4047
4048
4049       uv_loop_t *uv_getnameinfo_t.loop
4050              Loop  that started this getnameinfo request and where completion
4051              will be reported. Readonly.
4052
4053       char[NI_MAXHOST] uv_getnameinfo_t.host
4054              Char array containing the resulting host. It's null terminated.
4055
4056              Changed in version 1.3.0: the field is declared as public.
4057
4058
4059       char[NI_MAXSERV] uv_getnameinfo_t.service
4060              Char array containing the resulting service.  It's  null  termi‐
4061              nated.
4062
4063              Changed in version 1.3.0: the field is declared as public.
4064
4065
4066       SEE ALSO:
4067          The uv_req_t members also apply.
4068
4069   API
4070       int     uv_getaddrinfo(uv_loop_t    *loop,    uv_getaddrinfo_t    *req,
4071       uv_getaddrinfo_cb getaddrinfo_cb, const char *node,  const  char  *ser‐
4072       vice, const struct addrinfo *hints)
4073              Asynchronous getaddrinfo(3).
4074
4075              Either node or service may be NULL but not both.
4076
4077              hints  is a pointer to a struct addrinfo with additional address
4078              type constraints, or NULL. Consult man -s 3 getaddrinfo for more
4079              details.
4080
4081              Returns  0  on  success or an error code < 0 on failure. If suc‐
4082              cessful, the callback will get called  sometime  in  the  future
4083              with the lookup result, which is either:
4084
4085              • status  ==  0,  the  res argument points to a valid struct ad‐
4086                drinfo, or
4087
4088              • status < 0, the res argument is NULL. See  the  UV_EAI_*  con‐
4089                stants.
4090
4091              Call uv_freeaddrinfo() to free the addrinfo structure.
4092
4093              Changed  in version 1.3.0: the callback parameter is now allowed
4094              to be NULL, in which case the request will run synchronously.
4095
4096
4097       void uv_freeaddrinfo(struct addrinfo *ai)
4098              Free the struct addrinfo. Passing  NULL  is  allowed  and  is  a
4099              no-op.
4100
4101       int     uv_getnameinfo(uv_loop_t    *loop,    uv_getnameinfo_t    *req,
4102       uv_getnameinfo_cb getnameinfo_cb,  const  struct  sockaddr  *addr,  int
4103       flags)
4104              Asynchronous getnameinfo(3).
4105
4106              Returns  0  on  success or an error code < 0 on failure. If suc‐
4107              cessful, the callback will get called  sometime  in  the  future
4108              with  the  lookup result.  Consult man -s 3 getnameinfo for more
4109              details.
4110
4111              Changed in version 1.3.0: the callback parameter is now  allowed
4112              to be NULL, in which case the request will run synchronously.
4113
4114
4115       SEE ALSO:
4116          The uv_req_t API functions also apply.
4117
4118   Shared library handling
4119       libuv  provides  cross  platform utilities for loading shared libraries
4120       and retrieving symbols from them, using the following API.
4121
4122   Data types
4123       type uv_lib_t
4124              Shared library data type.
4125
4126   Public members
4127       N/A
4128
4129   API
4130       int uv_dlopen(const char *filename, uv_lib_t *lib)
4131              Opens a shared library. The filename is in utf-8. Returns  0  on
4132              success and -1 on error. Call uv_dlerror() to get the error mes‐
4133              sage.
4134
4135       void uv_dlclose(uv_lib_t *lib)
4136              Close the shared library.
4137
4138       int uv_dlsym(uv_lib_t *lib, const char *name, void **ptr)
4139              Retrieves a data pointer from a dynamic library. It is legal for
4140              a symbol to map to NULL. Returns 0 on success and -1 if the sym‐
4141              bol was not found.
4142
4143       const char *uv_dlerror(const uv_lib_t *lib)
4144              Returns the last uv_dlopen() or uv_dlsym() error message.
4145
4146   Threading and synchronization utilities
4147       libuv provides cross-platform implementations  for  multiple  threading
4148       and  synchronization  primitives.  The API largely follows the pthreads
4149       API.
4150
4151   Data types
4152       type uv_thread_t
4153              Thread data type.
4154
4155       typedef void (*uv_thread_cb)(void *arg)
4156              Callback that is invoked to initialize thread execution. arg  is
4157              the same value that was passed to uv_thread_create().
4158
4159       type uv_key_t
4160              Thread-local key data type.
4161
4162       type uv_once_t
4163              Once-only initializer data type.
4164
4165       type uv_mutex_t
4166              Mutex data type.
4167
4168       type uv_rwlock_t
4169              Read-write lock data type.
4170
4171       type uv_sem_t
4172              Semaphore data type.
4173
4174       type uv_cond_t
4175              Condition data type.
4176
4177       type uv_barrier_t
4178              Barrier data type.
4179
4180   API
4181   Threads
4182       type uv_thread_options_t
4183              Options    for    spawning    a    new    thread    (passed   to
4184              uv_thread_create_ex()).
4185
4186                 typedef struct uv_thread_options_s {
4187                   enum {
4188                     UV_THREAD_NO_FLAGS = 0x00,
4189                     UV_THREAD_HAS_STACK_SIZE = 0x01
4190                   } flags;
4191                   size_t stack_size;
4192                 } uv_thread_options_t;
4193
4194              More fields may be added to this struct at any time, so its  ex‐
4195              act layout and size should not be relied upon.
4196
4197              New in version 1.26.0.
4198
4199
4200       int uv_thread_create(uv_thread_t *tid, uv_thread_cb entry, void *arg)
4201              Changed in version 1.4.1: returns a UV_E* error code on failure
4202
4203
4204       int  uv_thread_create_ex(uv_thread_t  *tid,  const  uv_thread_options_t
4205       *params, uv_thread_cb entry, void *arg)
4206              Like uv_thread_create(), but additionally specifies options  for
4207              creating a new thread.
4208
4209              If UV_THREAD_HAS_STACK_SIZE is set, stack_size specifies a stack
4210              size for the new thread.  0 indicates  that  the  default  value
4211              should  be used, i.e. behaves as if the flag was not set.  Other
4212              values will be rounded up to the nearest page boundary.
4213
4214              New in version 1.26.0.
4215
4216
4217       int uv_thread_setaffinity(uv_thread_t *tid, char *cpumask,  char  *old‐
4218       mask, size_t mask_size)
4219              Sets the specified thread's affinity to cpumask, which is speci‐
4220              fied in bytes. Optionally returning the previous  affinity  set‐
4221              ting in oldmask.  On Unix, uses pthread_getaffinity_np(3) to get
4222              the affinity setting and maps the cpu_set_t to bytes in oldmask.
4223              Then  maps  the  bytes  in  cpumask  to  a  cpu_set_t  and  uses
4224              pthread_setaffinity_np(3). On Windows, maps the bytes in cpumask
4225              to  a bitmask and uses SetThreadAffinityMask() which returns the
4226              previous affinity setting.
4227
4228              The mask_size specifies the number of entries (bytes) in cpumask
4229              /     oldmask,     and    must    be    greater-than-or-equal-to
4230              uv_cpumask_size().
4231
4232              NOTE:
4233                 Thread affinity setting is not atomic on Windows. Unsupported
4234                 on macOS.
4235
4236              New in version 1.45.0.
4237
4238
4239       int   uv_thread_getaffinity(uv_thread_t  *tid,  char  *cpumask,  size_t
4240       mask_size)
4241              Gets the specified thread's affinity setting. On Unix, this maps
4242              the  cpu_set_t returned by pthread_getaffinity_np(3) to bytes in
4243              cpumask.
4244
4245              The  mask_size  specifies  the  number  of  entries  (bytes)  in
4246              cpumask, and must be greater-than-or-equal-to uv_cpumask_size().
4247
4248              NOTE:
4249                 Thread affinity getting is not atomic on Windows. Unsupported
4250                 on macOS.
4251
4252              New in version 1.45.0.
4253
4254
4255       int uv_thread_getcpu(void)
4256              Gets the CPU number on which the calling thread is running.
4257
4258              NOTE:
4259                 Currently only implemented on Windows, Linux and FreeBSD.
4260
4261              New in version 1.45.0.
4262
4263
4264       uv_thread_t uv_thread_self(void)
4265
4266       int uv_thread_join(uv_thread_t *tid)
4267
4268       int uv_thread_equal(const uv_thread_t *t1, const uv_thread_t *t2)
4269
4270   Thread-local storage
4271       NOTE:
4272          The total thread-local storage size may be limited. That is, it  may
4273          not be possible to create many TLS keys.
4274
4275       int uv_key_create(uv_key_t *key)
4276
4277       void uv_key_delete(uv_key_t *key)
4278
4279       void *uv_key_get(uv_key_t *key)
4280
4281       void uv_key_set(uv_key_t *key, void *value)
4282
4283   Once-only initialization
4284       Runs  a function once and only once. Concurrent calls to uv_once() with
4285       the same guard will block all  callers  except  one  (it's  unspecified
4286       which  one).   The  guard  should  be  initialized  statically with the
4287       UV_ONCE_INIT macro.
4288
4289       void uv_once(uv_once_t *guard, void (*callback)(void))
4290
4291   Mutex locks
4292       Functions return 0 on success or an error code < 0 (unless  the  return
4293       type is void, of course).
4294
4295       int uv_mutex_init(uv_mutex_t *handle)
4296
4297       int uv_mutex_init_recursive(uv_mutex_t *handle)
4298
4299       void uv_mutex_destroy(uv_mutex_t *handle)
4300
4301       void uv_mutex_lock(uv_mutex_t *handle)
4302
4303       int uv_mutex_trylock(uv_mutex_t *handle)
4304
4305       void uv_mutex_unlock(uv_mutex_t *handle)
4306
4307   Read-write locks
4308       Functions  return  0 on success or an error code < 0 (unless the return
4309       type is void, of course).
4310
4311       int uv_rwlock_init(uv_rwlock_t *rwlock)
4312
4313       void uv_rwlock_destroy(uv_rwlock_t *rwlock)
4314
4315       void uv_rwlock_rdlock(uv_rwlock_t *rwlock)
4316
4317       int uv_rwlock_tryrdlock(uv_rwlock_t *rwlock)
4318
4319       void uv_rwlock_rdunlock(uv_rwlock_t *rwlock)
4320
4321       void uv_rwlock_wrlock(uv_rwlock_t *rwlock)
4322
4323       int uv_rwlock_trywrlock(uv_rwlock_t *rwlock)
4324
4325       void uv_rwlock_wrunlock(uv_rwlock_t *rwlock)
4326
4327   Semaphores
4328       Functions return 0 on success or an error code < 0 (unless  the  return
4329       type is void, of course).
4330
4331       int uv_sem_init(uv_sem_t *sem, unsigned int value)
4332
4333       void uv_sem_destroy(uv_sem_t *sem)
4334
4335       void uv_sem_post(uv_sem_t *sem)
4336
4337       void uv_sem_wait(uv_sem_t *sem)
4338
4339       int uv_sem_trywait(uv_sem_t *sem)
4340
4341   Conditions
4342       Functions  return  0 on success or an error code < 0 (unless the return
4343       type is void, of course).
4344
4345       NOTE:
4346
4347          1. Callers should be prepared  to  deal  with  spurious  wakeups  on
4348             uv_cond_wait() and uv_cond_timedwait().
4349
4350          2. The  timeout parameter for uv_cond_timedwait() is relative to the
4351             time at which function is called.
4352
4353          3. On z/OS, the timeout parameter for  uv_cond_timedwait()  is  con‐
4354             verted  to  an absolute system time at which the wait expires. If
4355             the current system clock time passes the absolute time calculated
4356             before the condition is signaled, an ETIMEDOUT error results. Af‐
4357             ter the wait begins, the wait time is not affected by changes  to
4358             the system clock.
4359
4360       int uv_cond_init(uv_cond_t *cond)
4361
4362       void uv_cond_destroy(uv_cond_t *cond)
4363
4364       void uv_cond_signal(uv_cond_t *cond)
4365
4366       void uv_cond_broadcast(uv_cond_t *cond)
4367
4368       void uv_cond_wait(uv_cond_t *cond, uv_mutex_t *mutex)
4369
4370       int  uv_cond_timedwait(uv_cond_t  *cond,  uv_mutex_t  *mutex,  uint64_t
4371       timeout)
4372
4373   Barriers
4374       Functions return 0 on success or an error code < 0 (unless  the  return
4375       type is void, of course).
4376
4377       NOTE:
4378          uv_barrier_wait()  returns a value > 0 to an arbitrarily chosen "se‐
4379          rializer" thread to facilitate cleanup, i.e.
4380
4381              if (uv_barrier_wait(&barrier) > 0)
4382                  uv_barrier_destroy(&barrier);
4383
4384       int uv_barrier_init(uv_barrier_t *barrier, unsigned int count)
4385
4386       void uv_barrier_destroy(uv_barrier_t *barrier)
4387
4388       int uv_barrier_wait(uv_barrier_t *barrier)
4389
4390   Miscellaneous utilities
4391       This section contains miscellaneous functions that don't really  belong
4392       in any other section.
4393
4394   Data types
4395       type uv_buf_t
4396              Buffer data type.
4397
4398              char *uv_buf_t.base
4399                     Pointer to the base of the buffer.
4400
4401              size_t uv_buf_t.len
4402                     Total bytes in the buffer.
4403
4404                     NOTE:
4405                        On Windows this field is ULONG.
4406
4407       typedef void *(*uv_malloc_func)(size_t size)
4408              Replacement function for malloc(3).  See uv_replace_allocator().
4409
4410       typedef void *(*uv_realloc_func)(void *ptr, size_t size)
4411              Replacement       function       for       realloc(3).       See
4412              uv_replace_allocator().
4413
4414       typedef void *(*uv_calloc_func)(size_t count, size_t size)
4415              Replacement function for calloc(3).  See uv_replace_allocator().
4416
4417       typedef void (*uv_free_func)(void *ptr)
4418              Replacement function for free(3).  See uv_replace_allocator().
4419
4420       typedef void (*uv_random_cb)(uv_random_t *req, int status,  void  *buf,
4421       size_t buflen)
4422              Callback  passed  to  uv_random(). status is non-zero in case of
4423              error. The buf pointer is the same pointer that  was  passed  to
4424              uv_random().
4425
4426       type uv_file
4427              Cross platform representation of a file handle.
4428
4429       type uv_os_sock_t
4430              Cross platform representation of a socket handle.
4431
4432       type uv_os_fd_t
4433              Abstract  representation  of  a file descriptor. On Unix systems
4434              this is a typedef of int and on Windows a HANDLE.
4435
4436       type uv_pid_t
4437              Cross platform representation of a pid_t.
4438
4439              New in version 1.16.0.
4440
4441
4442       type uv_timeval_t
4443              Y2K38-unsafe data type for storing times with microsecond  reso‐
4444              lution.  Will be replaced with uv_timeval64_t in libuv v2.0.
4445
4446                 typedef struct {
4447                     long tv_sec;
4448                     long tv_usec;
4449                 } uv_timeval_t;
4450
4451       type uv_timeval64_t
4452              Y2K38-safe  data type for storing times with microsecond resolu‐
4453              tion.
4454
4455                 typedef struct {
4456                     int64_t tv_sec;
4457                     int32_t tv_usec;
4458                 } uv_timeval64_t;
4459
4460       type uv_timespec64_t
4461              Y2K38-safe data type for storing times with  nanosecond  resolu‐
4462              tion.
4463
4464                 typedef struct {
4465                     int64_t tv_sec;
4466                     int32_t tv_nsec;
4467                 } uv_timespec64_t;
4468
4469       enum uv_clock_id
4470              Clock source for uv_clock_gettime().
4471
4472                 typedef enum {
4473                   UV_CLOCK_MONOTONIC,
4474                   UV_CLOCK_REALTIME
4475                 } uv_clock_id;
4476
4477       type uv_rusage_t
4478              Data type for resource usage results.
4479
4480                 typedef struct {
4481                     uv_timeval_t ru_utime; /* user CPU time used */
4482                     uv_timeval_t ru_stime; /* system CPU time used */
4483                     uint64_t ru_maxrss; /* maximum resident set size */
4484                     uint64_t ru_ixrss; /* integral shared memory size (X) */
4485                     uint64_t ru_idrss; /* integral unshared data size (X) */
4486                     uint64_t ru_isrss; /* integral unshared stack size (X) */
4487                     uint64_t ru_minflt; /* page reclaims (soft page faults) (X) */
4488                     uint64_t ru_majflt; /* page faults (hard page faults) */
4489                     uint64_t ru_nswap; /* swaps (X) */
4490                     uint64_t ru_inblock; /* block input operations */
4491                     uint64_t ru_oublock; /* block output operations */
4492                     uint64_t ru_msgsnd; /* IPC messages sent (X) */
4493                     uint64_t ru_msgrcv; /* IPC messages received (X) */
4494                     uint64_t ru_nsignals; /* signals received (X) */
4495                     uint64_t ru_nvcsw; /* voluntary context switches (X) */
4496                     uint64_t ru_nivcsw; /* involuntary context switches (X) */
4497                 } uv_rusage_t;
4498
4499              Members  marked  with  (X)  are  unsupported  on  Windows.   See
4500              getrusage(2) for supported fields on UNIX-like platforms.
4501
4502              The maximum resident set size is reported in kilobytes, the unit
4503              most platforms use natively.
4504
4505       type uv_cpu_info_t
4506              Data type for CPU information.
4507
4508                 typedef struct uv_cpu_info_s {
4509                     char* model;
4510                     int speed;
4511                     struct uv_cpu_times_s {
4512                         uint64_t user; /* milliseconds */
4513                         uint64_t nice; /* milliseconds */
4514                         uint64_t sys; /* milliseconds */
4515                         uint64_t idle; /* milliseconds */
4516                         uint64_t irq; /* milliseconds */
4517                     } cpu_times;
4518                 } uv_cpu_info_t;
4519
4520       type uv_interface_address_t
4521              Data type for interface addresses.
4522
4523                 typedef struct uv_interface_address_s {
4524                     char* name;
4525                     char phys_addr[6];
4526                     int is_internal;
4527                     union {
4528                         struct sockaddr_in address4;
4529                         struct sockaddr_in6 address6;
4530                     } address;
4531                     union {
4532                         struct sockaddr_in netmask4;
4533                         struct sockaddr_in6 netmask6;
4534                     } netmask;
4535                 } uv_interface_address_t;
4536
4537       type uv_passwd_t
4538              Data type for password file information.
4539
4540                 typedef struct uv_passwd_s {
4541                     char* username;
4542                     long uid;
4543                     long gid;
4544                     char* shell;
4545                     char* homedir;
4546                 } uv_passwd_t;
4547
4548       type uv_utsname_t
4549              Data type for operating system name and version information.
4550
4551                 typedef struct uv_utsname_s {
4552                     char sysname[256];
4553                     char release[256];
4554                     char version[256];
4555                     char machine[256];
4556                 } uv_utsname_t;
4557
4558       type uv_env_item_t
4559              Data type for environment variable storage.
4560
4561                 typedef struct uv_env_item_s {
4562                     char* name;
4563                     char* value;
4564                 } uv_env_item_t;
4565
4566       type uv_random_t
4567              Random data request type.
4568
4569   API
4570       uv_handle_type uv_guess_handle(uv_file file)
4571              Used  to  detect what type of stream should be used with a given
4572              file descriptor. Usually this will be used during initialization
4573              to guess the type of the stdio streams.
4574
4575              For  isatty(3)  equivalent  functionality  use this function and
4576              test for UV_TTY.
4577
4578       int  uv_replace_allocator(uv_malloc_func  malloc_func,  uv_realloc_func
4579       realloc_func, uv_calloc_func calloc_func, uv_free_func free_func)
4580              New in version 1.6.0.
4581
4582
4583              Override the use of the standard library's malloc(3), calloc(3),
4584              realloc(3), free(3), memory allocation functions.
4585
4586              This function must be called before any other libuv function  is
4587              called  or  after  all  resources have been freed and thus libuv
4588              doesn't reference any allocated memory chunk.
4589
4590              On success, it returns 0, if any of  the  function  pointers  is
4591              NULL it returns UV_EINVAL.
4592
4593              WARNING:
4594                 There  is no protection against changing the allocator multi‐
4595                 ple times. If the user changes it they  are  responsible  for
4596                 making  sure the allocator is changed while no memory was al‐
4597                 located with the previous allocator, or that they are compat‐
4598                 ible.
4599
4600              WARNING:
4601                 Allocator must be thread-safe.
4602
4603       void uv_library_shutdown(void);
4604              New in version 1.38.0.
4605
4606
4607              Release  any global state that libuv is holding onto. Libuv will
4608              normally do so automatically when it is unloaded but it  can  be
4609              instructed to perform cleanup manually.
4610
4611              WARNING:
4612                 Only call uv_library_shutdown() once.
4613
4614              WARNING:
4615                 Don't  call  uv_library_shutdown() when there are still event
4616                 loops or I/O requests active.
4617
4618              WARNING:
4619                 Don't     call     libuv     functions     after      calling
4620                 uv_library_shutdown().
4621
4622       uv_buf_t uv_buf_init(char *base, unsigned int len)
4623              Constructor for uv_buf_t.
4624
4625              Due to platform differences the user cannot rely on the ordering
4626              of the base and len members of the uv_buf_t struct. The user  is
4627              responsible  for freeing base after the uv_buf_t is done. Return
4628              struct passed by value.
4629
4630       char **uv_setup_args(int argc, char **argv)
4631              Store the program arguments. Required for getting / setting  the
4632              process  title  or the executable path. Libuv may take ownership
4633              of the memory that argv  points  to.  This  function  should  be
4634              called exactly once, at program start-up.
4635
4636              Example:
4637
4638                 argv = uv_setup_args(argc, argv);  /* May return a copy of argv. */
4639
4640       int uv_get_process_title(char *buffer, size_t size)
4641              Gets   the   title   of  the  current  process.  You  must  call
4642              uv_setup_args before calling this function on Unix and AIX  sys‐
4643              tems.  If  uv_setup_args has not been called on systems that re‐
4644              quire it, then UV_ENOBUFS is returned. If buffer is NULL or size
4645              is  zero, UV_EINVAL is returned.  If size cannot accommodate the
4646              process title and terminating nul character,  the  function  re‐
4647              turns UV_ENOBUFS.
4648
4649              NOTE:
4650                 On  BSD systems, uv_setup_args is needed for getting the ini‐
4651                 tial process title. The process title  returned  will  be  an
4652                 empty string until either uv_setup_args or uv_set_process_ti‐
4653                 tle is called.
4654
4655              Changed in version 1.18.1:  now  thread-safe  on  all  supported
4656              platforms.
4657
4658
4659              Changed in version 1.39.0: now returns an error if uv_setup_args
4660              is needed but hasn't been called.
4661
4662
4663       int uv_set_process_title(const char *title)
4664              Sets the current process title. You must call uv_setup_args  be‐
4665              fore   calling  this  function  on  Unix  and  AIX  systems.  If
4666              uv_setup_args has not been called on systems  that  require  it,
4667              then UV_ENOBUFS is returned. On platforms with a fixed size buf‐
4668              fer for the process title the contents of title will  be  copied
4669              to  the buffer and truncated if larger than the available space.
4670              Other platforms will return UV_ENOMEM if  they  cannot  allocate
4671              enough space to duplicate the contents of title.
4672
4673              Changed  in  version  1.18.1:  now  thread-safe on all supported
4674              platforms.
4675
4676
4677              Changed in version 1.39.0: now returns an error if uv_setup_args
4678              is needed but hasn't been called.
4679
4680
4681       int uv_resident_set_memory(size_t *rss)
4682              Gets the resident set size (RSS) for the current process.
4683
4684       int uv_uptime(double *uptime)
4685              Gets  the current system uptime. Depending on the system full or
4686              fractional seconds are returned.
4687
4688       int uv_getrusage(uv_rusage_t *rusage)
4689              Gets the resource usage measures for the current process.
4690
4691              NOTE:
4692                 On Windows not all fields are set, the unsupported fields are
4693                 filled with zeroes.  See uv_rusage_t for more details.
4694
4695       uv_pid_t uv_os_getpid(void)
4696              Returns the current process ID.
4697
4698              New in version 1.18.0.
4699
4700
4701       uv_pid_t uv_os_getppid(void)
4702              Returns the parent process ID.
4703
4704              New in version 1.16.0.
4705
4706
4707       unsigned int uv_available_parallelism(void)
4708              Returns  an estimate of the default amount of parallelism a pro‐
4709              gram should use. Always returns a non-zero value.
4710
4711              On Linux, inspects the calling thread's CPU affinity mask to de‐
4712              termine if it has been pinned to specific CPUs.
4713
4714              On  Windows,  the  available parallelism may be underreported on
4715              systems with more than 64 logical CPUs.
4716
4717              On other platforms, reports the number of CPUs that the  operat‐
4718              ing system considers to be online.
4719
4720              New in version 1.44.0.
4721
4722
4723       int uv_cpu_info(uv_cpu_info_t **cpu_infos, int *count)
4724              Gets information about the CPUs on the system. The cpu_infos ar‐
4725              ray will  have  count  elements  and  needs  to  be  freed  with
4726              uv_free_cpu_info().
4727
4728              Use uv_available_parallelism() if you need to know how many CPUs
4729              are available for threads or child processes.
4730
4731       void uv_free_cpu_info(uv_cpu_info_t *cpu_infos, int count)
4732              Frees   the   cpu_infos   array   previously   allocated    with
4733              uv_cpu_info().
4734
4735       int uv_cpumask_size(void)
4736              Returns  the  maximum  size  of the mask used for process/thread
4737              affinities, or UV_ENOTSUP if affinities are not supported on the
4738              current platform.
4739
4740              New in version 1.45.0.
4741
4742
4743       int   uv_interface_addresses(uv_interface_address_t   **addresses,  int
4744       *count)
4745              Gets address information about the  network  interfaces  on  the
4746              system.  An array of count elements is allocated and returned in
4747              addresses.   It   must   be   freed   by   the   user,   calling
4748              uv_free_interface_addresses().
4749
4750       void uv_free_interface_addresses(uv_interface_address_t *addresses, int
4751       count)
4752              Free an array of uv_interface_address_t which  was  returned  by
4753              uv_interface_addresses().
4754
4755       void uv_loadavg(double avg[3])
4756              Gets           the          load          average.          See:
4757              https://en.wikipedia.org/wiki/Load_(computing)
4758
4759              NOTE:
4760                 Returns [0,0,0] on Windows (i.e., it's not implemented).
4761
4762       int uv_ip4_addr(const char *ip, int port, struct sockaddr_in *addr)
4763              Convert a string containing an IPv4 addresses to a binary struc‐
4764              ture.
4765
4766       int uv_ip6_addr(const char *ip, int port, struct sockaddr_in6 *addr)
4767              Convert a string containing an IPv6 addresses to a binary struc‐
4768              ture.
4769
4770       int uv_ip4_name(const struct sockaddr_in *src, char *dst, size_t size)
4771              Convert a binary structure  containing  an  IPv4  address  to  a
4772              string.
4773
4774       int uv_ip6_name(const struct sockaddr_in6 *src, char *dst, size_t size)
4775              Convert  a  binary  structure  containing  an  IPv6 address to a
4776              string.
4777
4778       int uv_ip_name(const struct sockaddr *src, char *dst, size_t size)
4779              Convert a binary structure containing an IPv4 address or an IPv6
4780              address to a string.
4781
4782       int uv_inet_ntop(int af, const void *src, char *dst, size_t size)
4783
4784       int uv_inet_pton(int af, const char *src, void *dst)
4785              Cross-platform  IPv6-capable  implementation of inet_ntop(3) and
4786              inet_pton(3). On success they return 0. In  case  of  error  the
4787              target dst pointer is unmodified.
4788
4789       UV_IF_NAMESIZE
4790              Maximum  IPv6  interface identifier name length.  Defined as IF‐
4791              NAMSIZ on Unix and IF_NAMESIZE on Linux and Windows.
4792
4793              New in version 1.16.0.
4794
4795
4796       int uv_if_indextoname(unsigned int ifindex, char *buffer, size_t *size)
4797              IPv6-capable implementation of if_indextoname(3).  When  called,
4798              *size indicates the length of the buffer, which is used to store
4799              the result.  On success, zero is returned, buffer  contains  the
4800              interface  name,  and  *size represents the string length of the
4801              buffer, excluding the NUL terminator byte from *size. On  error,
4802              a  negative result is returned. If buffer is not large enough to
4803              hold the result, UV_ENOBUFS is returned,  and  *size  represents
4804              the  necessary  size in bytes, including the NUL terminator byte
4805              into the *size.
4806
4807              On Unix, the returned interface name can be used directly as  an
4808              interface    identifier   in   scoped   IPv6   addresses,   e.g.
4809              fe80::abc:def1:2345%en0.
4810
4811              On Windows, the returned interface cannot be used as  an  inter‐
4812              face  identifier,  as  Windows  uses numerical interface identi‐
4813              fiers, e.g.  fe80::abc:def1:2345%5.
4814
4815              To get an interface identifier in  a  cross-platform  compatible
4816              way, use uv_if_indextoiid().
4817
4818              Example:
4819
4820                 char ifname[UV_IF_NAMESIZE];
4821                 size_t size = sizeof(ifname);
4822                 uv_if_indextoname(sin6->sin6_scope_id, ifname, &size);
4823
4824              New in version 1.16.0.
4825
4826
4827       int uv_if_indextoiid(unsigned int ifindex, char *buffer, size_t *size)
4828              Retrieves  a network interface identifier suitable for use in an
4829              IPv6 scoped address. On Windows, returns the numeric ifindex  as
4830              a string. On all other platforms, uv_if_indextoname() is called.
4831              The result is written  to  buffer,  with  *size  indicating  the
4832              length  of buffer. If buffer is not large enough to hold the re‐
4833              sult, then UV_ENOBUFS is  returned,  and  *size  represents  the
4834              size, including the NUL byte, required to hold the result.
4835
4836              See uv_if_indextoname for further details.
4837
4838              New in version 1.16.0.
4839
4840
4841       int uv_exepath(char *buffer, size_t *size)
4842              Gets  the  executable  path.  You must call uv_setup_args before
4843              calling this function.
4844
4845       int uv_cwd(char *buffer, size_t *size)
4846              Gets the current working directory, and stores it in buffer.  If
4847              the  current  working  directory  is too large to fit in buffer,
4848              this function returns UV_ENOBUFS, and sets size to the  required
4849              length, including the null terminator.
4850
4851              Changed  in  version 1.1.0: On Unix the path no longer ends in a
4852              slash.
4853
4854
4855              Changed in version 1.9.0: the returned length includes the  ter‐
4856              minating  null byte on UV_ENOBUFS, and the buffer is null termi‐
4857              nated on success.
4858
4859
4860       int uv_chdir(const char *dir)
4861              Changes the current working directory.
4862
4863       int uv_os_homedir(char *buffer, size_t *size)
4864              Gets the current user's home directory. On Windows,  uv_os_home‐
4865              dir()  first  checks  the USERPROFILE environment variable using
4866              GetEnvironmentVariableW(). If USERPROFILE is not  set,  GetUser‐
4867              ProfileDirectoryW()  is  called. On all other operating systems,
4868              uv_os_homedir() first checks the HOME environment variable using
4869              getenv(3).  If  HOME  is  not  set, getpwuid_r(3) is called. The
4870              user's home directory is stored in buffer. When  uv_os_homedir()
4871              is called, size indicates the maximum size of buffer. On success
4872              size is set to the string length of buffer. On UV_ENOBUFS  fail‐
4873              ure size is set to the required length for buffer, including the
4874              null byte.
4875
4876              WARNING:
4877                 uv_os_homedir() is not thread safe.
4878
4879              New in version 1.6.0.
4880
4881
4882       int uv_os_tmpdir(char *buffer, size_t *size)
4883              Gets the temp directory. On Windows,  uv_os_tmpdir()  uses  Get‐
4884              TempPathW().   On  all  other  operating systems, uv_os_tmpdir()
4885              uses the first environment variable found in  the  ordered  list
4886              TMPDIR, TMP, TEMP, and TEMPDIR.  If none of these are found, the
4887              path "/tmp" is used, or, on Android, "/data/local/tmp" is  used.
4888              The  temp  directory is stored in buffer. When uv_os_tmpdir() is
4889              called, size indicates the maximum size of buffer.   On  success
4890              size  is  set to the string length of buffer (which does not in‐
4891              clude the terminating null). On UV_ENOBUFS failure size  is  set
4892              to the required length for buffer, including the null byte.
4893
4894              WARNING:
4895                 uv_os_tmpdir() is not thread safe.
4896
4897              New in version 1.9.0.
4898
4899
4900       int uv_os_get_passwd(uv_passwd_t *pwd)
4901              Gets  a subset of the password file entry for the current effec‐
4902              tive uid (not the real uid). The  populated  data  includes  the
4903              username,  euid,  gid, shell, and home directory. On non-Windows
4904              systems, all data comes from getpwuid_r(3). On Windows, uid  and
4905              gid  are set to -1 and have no meaning, and shell is NULL. After
4906              successfully calling this function, the memory allocated to  pwd
4907              needs to be freed with uv_os_free_passwd().
4908
4909              New in version 1.9.0.
4910
4911
4912       void uv_os_free_passwd(uv_passwd_t *pwd)
4913              Frees    the    pwd    memory    previously    allocated    with
4914              uv_os_get_passwd().
4915
4916              New in version 1.9.0.
4917
4918
4919       uint64_t uv_get_free_memory(void)
4920              Gets the amount of free memory available in the system,  as  re‐
4921              ported by the kernel (in bytes). Returns 0 when unknown.
4922
4923       uint64_t uv_get_total_memory(void)
4924              Gets  the  total  amount  of  physical  memory in the system (in
4925              bytes).  Returns 0 when unknown.
4926
4927       uint64_t uv_get_constrained_memory(void)
4928              Gets the total amount of memory available  to  the  process  (in
4929              bytes)  based  on  limits imposed by the OS. If there is no such
4930              constraint, or the constraint is  unknown,  0  is  returned.  If
4931              there  is  a  constraining mechanism, but there is no constraint
4932              set, UINT64_MAX is returned. Note that it  is  not  unusual  for
4933              this    value    to    be    less    than    or   greater   than
4934              uv_get_total_memory().
4935
4936              NOTE:
4937                 This function currently only  returns  a  non-zero  value  on
4938                 Linux,  based  on cgroups if it is present, and on z/OS based
4939                 on RLIMIT_MEMLIMIT.
4940
4941              New in version 1.29.0.
4942
4943
4944       uint64_t uv_get_available_memory(void)
4945              Gets the amount of free memory that is still  available  to  the
4946              process  (in  bytes).  This differs from uv_get_free_memory() in
4947              that it takes into account any limits  imposed  by  the  OS.  If
4948              there  is  no such constraint, or the constraint is unknown, the
4949              amount returned will be identical to uv_get_free_memory().
4950
4951              NOTE:
4952                 This function currently only returns a value that is  differ‐
4953                 ent from what uv_get_free_memory() reports on Linux, based on
4954                 cgroups if it is present.
4955
4956              New in version 1.45.0.
4957
4958
4959       uint64_t uv_hrtime(void)
4960              Returns the current high-resolution timestamp. This is expressed
4961              in nanoseconds. It is relative to an arbitrary time in the past.
4962              It is not related to the time of day and therefore  not  subject
4963              to clock drift. The primary use is for measuring performance be‐
4964              tween intervals.
4965
4966              NOTE:
4967                 Not every platform can support  nanosecond  resolution;  how‐
4968                 ever, this value will always be in nanoseconds.
4969
4970       int uv_clock_gettime(uv_clock_id clock_id, uv_timespec64_t *ts)
4971              Obtain  the current system time from a high-resolution real-time
4972              or monotonic clock source.
4973
4974              The real-time clock counts from the UNIX epoch (1970-01-01)  and
4975              is subject to time adjustments; it can jump back in time.
4976
4977              The  monotonic  clock counts from an arbitrary point in the past
4978              and never jumps back in time.
4979
4980              New in version 1.45.0.
4981
4982
4983       void uv_print_all_handles(uv_loop_t *loop, FILE *stream)
4984              Prints all handles associated with the given loop to  the  given
4985              stream.
4986
4987              Example:
4988
4989                 uv_print_all_handles(uv_default_loop(), stderr);
4990                 /*
4991                 [--I] signal   0x1a25ea8
4992                 [-AI] async    0x1a25cf0
4993                 [R--] idle     0x1a7a8c8
4994                 */
4995
4996              The format is [flags] handle-type handle-address. For flags:
4997
4998R is printed for a handle that is referenced
4999
5000A is printed for a handle that is active
5001
5002I is printed for a handle that is internal
5003
5004              WARNING:
5005                 This  function  is  meant  for  ad hoc debugging, there is no
5006                 API/ABI stability guarantees.
5007
5008              New in version 1.8.0.
5009
5010
5011       void uv_print_active_handles(uv_loop_t *loop, FILE *stream)
5012              This is the same as uv_print_all_handles()  except  only  active
5013              handles are printed.
5014
5015              WARNING:
5016                 This  function  is  meant  for  ad hoc debugging, there is no
5017                 API/ABI stability guarantees.
5018
5019              New in version 1.8.0.
5020
5021
5022       int uv_os_environ(uv_env_item_t **envitems, int *count)
5023              Retrieves all environment variables. This function will allocate
5024              memory which must be freed by calling uv_os_free_environ().
5025
5026              WARNING:
5027                 This function is not thread safe.
5028
5029              New in version 1.31.0.
5030
5031
5032       void uv_os_free_environ(uv_env_item_t *envitems, int count);
5033              Frees  the  memory  allocated  for  the environment variables by
5034              uv_os_environ().
5035
5036              New in version 1.31.0.
5037
5038
5039       int uv_os_getenv(const char *name, char *buffer, size_t *size)
5040              Retrieves the environment variable specified by name, copies its
5041              value  into  buffer,  and  sets size to the string length of the
5042              value. When calling this function,  size  must  be  set  to  the
5043              amount of storage available in buffer, including the null termi‐
5044              nator. If the environment variable exceeds the storage available
5045              in buffer, UV_ENOBUFS is returned, and size is set to the amount
5046              of storage required to hold the value. If no  matching  environ‐
5047              ment variable exists, UV_ENOENT is returned.
5048
5049              WARNING:
5050                 This function is not thread safe.
5051
5052              New in version 1.12.0.
5053
5054
5055       int uv_os_setenv(const char *name, const char *value)
5056              Creates  or  updates  the environment variable specified by name
5057              with value.
5058
5059              WARNING:
5060                 This function is not thread safe.
5061
5062              New in version 1.12.0.
5063
5064
5065       int uv_os_unsetenv(const char *name)
5066              Deletes the environment variable specified by name. If  no  such
5067              environment variable exists, this function returns successfully.
5068
5069              WARNING:
5070                 This function is not thread safe.
5071
5072              New in version 1.12.0.
5073
5074
5075       int uv_os_gethostname(char *buffer, size_t *size)
5076              Returns  the hostname as a null-terminated string in buffer, and
5077              sets size to the string length of  the  hostname.  When  calling
5078              this  function, size must be set to the amount of storage avail‐
5079              able in buffer, including the null terminator. If  the  hostname
5080              exceeds the storage available in buffer, UV_ENOBUFS is returned,
5081              and size is set to the amount of storage required  to  hold  the
5082              value.
5083
5084              New in version 1.12.0.
5085
5086
5087              Changed  in  version 1.26.0: UV_MAXHOSTNAMESIZE is available and
5088              represents the maximum buffer size required to store a  hostname
5089              and terminating nul character.
5090
5091
5092       int uv_os_getpriority(uv_pid_t pid, int *priority)
5093              Retrieves  the  scheduling  priority of the process specified by
5094              pid. The returned value of priority is between -20 (high  prior‐
5095              ity) and 19 (low priority).
5096
5097              NOTE:
5098                 On  Windows,  the  returned  priority  will  equal one of the
5099                 UV_PRIORITY constants.
5100
5101              New in version 1.23.0.
5102
5103
5104       int uv_os_setpriority(uv_pid_t pid, int priority)
5105              Sets the scheduling priority of the process  specified  by  pid.
5106              The  priority  value range is between -20 (high priority) and 19
5107              (low priority).  The constants UV_PRIORITY_LOW,  UV_PRIORITY_BE‐
5108              LOW_NORMAL,     UV_PRIORITY_NORMAL,    UV_PRIORITY_ABOVE_NORMAL,
5109              UV_PRIORITY_HIGH, and UV_PRIORITY_HIGHEST are also provided  for
5110              convenience.
5111
5112              NOTE:
5113                 On  Windows,  this  function utilizes SetPriorityClass(). The
5114                 priority argument is mapped to a Windows priority class. When
5115                 retrieving the process priority, the result will equal one of
5116                 the UV_PRIORITY constants,  and  not  necessarily  the  exact
5117                 value of priority.
5118
5119              NOTE:
5120                 On  Windows, setting PRIORITY_HIGHEST will only work for ele‐
5121                 vated user, for others it will be silently reduced to  PRIOR‐
5122                 ITY_HIGH.
5123
5124              NOTE:
5125                 On  IBM i PASE, the highest process priority is -10. The con‐
5126                 stant UV_PRIORITY_HIGHEST is  -10,  UV_PRIORITY_HIGH  is  -7,
5127                 UV_PRIORITY_ABOVE_NORMAL  is  -4,  UV_PRIORITY_NORMAL  is  0,
5128                 UV_PRIORITY_BELOW_NORMAL is 15 and UV_PRIORITY_LOW is 39.
5129
5130              NOTE:
5131                 On IBM i PASE, you are not allowed to  change  your  priority
5132                 unless  you have the *JOBCTL special authority (even to lower
5133                 it).
5134
5135              New in version 1.23.0.
5136
5137
5138       int uv_os_uname(uv_utsname_t *buffer)
5139              Retrieves system information in buffer. The populated  data  in‐
5140              cludes the operating system name, release, version, and machine.
5141              On non-Windows systems, uv_os_uname() is a thin  wrapper  around
5142              uname(2).  Returns  zero  on success, and a non-zero error value
5143              otherwise.
5144
5145              New in version 1.25.0.
5146
5147
5148       int uv_gettimeofday(uv_timeval64_t *tv)
5149              Cross-platform implementation of gettimeofday(2).  The  timezone
5150              argument to gettimeofday() is not supported, as it is considered
5151              obsolete.
5152
5153              New in version 1.28.0.
5154
5155
5156       int uv_random(uv_loop_t *loop, uv_random_t *req, void *buf, size_t  bu‐
5157       flen, unsigned int flags, uv_random_cb cb)
5158              Fill  buf  with  exactly  buflen cryptographically strong random
5159              bytes acquired from the system CSPRNG. flags is reserved for fu‐
5160              ture extension and must currently be 0.
5161
5162              Short reads are not possible. When less than buflen random bytes
5163              are available, a non-zero error value is returned or  passed  to
5164              the callback.
5165
5166              The  synchronous  version may block indefinitely when not enough
5167              entropy is available. The asynchronous version may not ever fin‐
5168              ish when the system is low on entropy.
5169
5170              Sources of entropy:
5171
5172              • Windows:  RtlGenRandom  <https://docs.microsoft.com/en-us/win
5173                dows/desktop/api/ntsecapi/nf-ntsecapi-rtlgenrandom>_.
5174
5175              • Linux, Android: getrandom(2) if available, or urandom(4) after
5176                reading from /dev/random once, or the KERN_RANDOM sysctl(2).
5177
5178              • FreeBSD:            getrandom(2)            <https://www.free
5179                bsd.org/cgi/man.cgi?query=getrandom&sektion=2>_, or /dev/uran‐
5180                dom after reading from /dev/random once.
5181
5182              • NetBSD: KERN_ARND sysctl(7) <https://man.netbsd.org/sysctl.7>_
5183
5184              • macOS,  OpenBSD: getentropy(2) <https://man.openbsd.org/geten
5185                tropy.2>_ if available, or  /dev/urandom  after  reading  from
5186                /dev/random once.
5187
5188              • AIX: /dev/random.
5189
5190              • IBM i: /dev/urandom.
5191
5192              • Other UNIX: /dev/urandom after reading from /dev/random once.
5193
5194              Returns
5195                     0  on  success, or an error code < 0 on failure. The con‐
5196                     tents of buf is undefined after an error.
5197
5198              NOTE:
5199                 When using the synchronous version, both loop and req parame‐
5200                 ters are not used and can be set to NULL.
5201
5202              New in version 1.33.0.
5203
5204
5205       void uv_sleep(unsigned int msec)
5206              Causes the calling thread to sleep for msec milliseconds.
5207
5208              New in version 1.34.0.
5209
5210
5211   String manipulation functions
5212       These  string utilities are needed internally for dealing with Windows,
5213       and are exported to allow clients to work uniformly with this data when
5214       the libuv API is not complete.
5215
5216       size_t    uv_utf16_length_as_wtf8(const    uint16_t   *utf16,   ssize_t
5217       utf16_len)
5218              Get the length of a UTF-16 (or UCS-2) utf16 value after convert‐
5219              ing  it  to  WTF-8. If utf16 is NUL terminated, utf16_len can be
5220              set to -1, otherwise it must be specified.
5221
5222              New in version 1.47.0.
5223
5224
5225       int uv_utf16_to_wtf8(const uint16_t  *utf16,  ssize_t  utf16_len,  char
5226       **wtf8_ptr, size_t *wtf8_len_ptr)
5227              Convert  UTF-16  (or  UCS-2)  data  in  utf16  to  WTF-8 data in
5228              *wtf8_ptr. The utf16_len count (in characters) gives the  length
5229              of  utf16.  If  utf16 is NUL terminated, utf16_len can be set to
5230              -1, otherwise it must be specified. If wtf8_ptr is NULL, no  re‐
5231              sult    will   be   computed,   but   the   length   (equal   to
5232              uv_utf16_length_as_wtf8)  will  be  stored  in   wtf8_ptr.    If
5233              *wtf8_ptr  is  NULL,  space for the conversion will be allocated
5234              and returned in wtf8_ptr and the  length  will  be  returned  in
5235              wtf8_len_ptr.  Otherwise, the length of *wtf8_ptr must be passed
5236              in wtf8_len_ptr. The wtf8_ptr must contain an extra space for an
5237              extra  NUL  after  the  result.   If  the  result  is truncated,
5238              UV_ENOBUFS will be returned and wtf8_len_ptr will be the  length
5239              of the required wtf8_ptr to contain the whole result.
5240
5241              New in version 1.47.0.
5242
5243
5244       ssize_t uv_wtf8_length_as_utf16(const char *wtf8)
5245              Get  the  length  in  characters  of a NUL-terminated WTF-8 wtf8
5246              value after converting it to UTF-16 (or  UCS-2),  including  NUL
5247              terminator.
5248
5249              New in version 1.47.0.
5250
5251
5252       void   uv_wtf8_to_utf16(const   char  *utf8,  uint16_t  *utf16,  size_t
5253       utf16_len)
5254              Convert NUL-terminated WTF-8 data in wtf8 to UTF-16  (or  UCS-2)
5255              data  in utf16. The utf16_len count (in characters) must include
5256              space for the NUL terminator.
5257
5258              New in version 1.47.0.
5259
5260
5261   Metrics operations
5262       libuv provides a metrics API to track various  internal  operations  of
5263       the event loop.
5264
5265   Data types
5266       type uv_metrics_t
5267              The  struct  that contains event loop metrics. It is recommended
5268              to retrieve these metrics in a uv_prepare_cb in  order  to  make
5269              sure there are no inconsistencies with the metrics counters.
5270
5271                 typedef struct {
5272                     uint64_t loop_count;
5273                     uint64_t events;
5274                     uint64_t events_waiting;
5275                     /* private */
5276                     uint64_t* reserved[13];
5277                 } uv_metrics_t;
5278
5279   Public members
5280       uint64_t uv_metrics_t.loop_count
5281              Number of event loop iterations.
5282
5283       uint64_t uv_metrics_t.events
5284              Number of events that have been processed by the event handler.
5285
5286       uint64_t uv_metrics_t.events_waiting
5287              Number  of  events  that  were  waiting to be processed when the
5288              event provider was called.
5289
5290   API
5291       uint64_t uv_metrics_idle_time(uv_loop_t *loop)
5292              Retrieve the amount of time the event loop has been idle in  the
5293              kernel's  event  provider  (e.g. epoll_wait). The call is thread
5294              safe.
5295
5296              The return value is the accumulated time spent idle in the  ker‐
5297              nel's  event  provider starting from when the uv_loop_t was con‐
5298              figured to collect the idle time.
5299
5300              NOTE:
5301                 The  event  loop  will  not  begin  accumulating  the   event
5302                 provider's  idle  time  until  calling uv_loop_configure with
5303                 UV_METRICS_IDLE_TIME.
5304
5305              New in version 1.39.0.
5306
5307
5308       int uv_metrics_info(uv_loop_t *loop, uv_metrics_t *metrics)
5309              Copy the current set  of  event  loop  metrics  to  the  metrics
5310              pointer.
5311
5312              New in version 1.45.0.
5313
5314
5315   User guide
5316       WARNING:
5317          The  contents of this guide have been recently incorporated into the
5318          libuv documentation and it hasn't gone through thorough review  yet.
5319          If  you  spot  a mistake please file an issue, or better yet, open a
5320          pull request!
5321
5322   Introduction
5323       This 'book' is a small set of tutorials about using  libuv  as  a  high
5324       performance  evented  I/O  library which offers the same API on Windows
5325       and Unix.
5326
5327       It is meant to cover the main areas of libuv, but is not  a  comprehen‐
5328       sive  reference  discussing  every  function  and  data  structure. The
5329       official libuv documentation may be consulted for full details.
5330
5331       This book is still a work in progress, so sections may  be  incomplete,
5332       but I hope you will enjoy it as it grows.
5333
5334   Who this book is for
5335       If you are reading this book, you are either:
5336
5337       1. a systems programmer, creating low-level programs such as daemons or
5338          network services and clients. You have found that the event loop ap‐
5339          proach is well suited for your application and decided to use libuv.
5340
5341       2. a  node.js module writer, who wants to wrap platform APIs written in
5342          C or C++ with a set of (a)synchronous APIs that are exposed to Java‐
5343          Script.  You  will  use  libuv purely in the context of node.js. For
5344          this you will require some other resources  as  the  book  does  not
5345          cover parts specific to v8/node.js.
5346
5347       This  book assumes that you are comfortable with the C programming lan‐
5348       guage.
5349
5350   Background
5351       The node.js project began in 2009 as a JavaScript environment decoupled
5352       from  the  browser. Using Google's V8 and Marc Lehmann's libev, node.js
5353       combined a model of I/O -- evented -- with a  language  that  was  well
5354       suited  to  the style of programming; due to the way it had been shaped
5355       by browsers. As node.js grew in popularity, it was important to make it
5356       work  on Windows, but libev ran only on Unix. The Windows equivalent of
5357       kernel event notification mechanisms like kqueue or  (e)poll  is  IOCP.
5358       libuv  was  an  abstraction around libev or IOCP depending on the plat‐
5359       form, providing users an API based on libev.  In the  node-v0.9.0  ver‐
5360       sion of libuv libev was removed.
5361
5362       Since  then  libuv  has  continued  to mature and become a high quality
5363       standalone library for system programming. Users outside of node.js in‐
5364       clude  Mozilla's  Rust  programming language, and a variety of language
5365       bindings.
5366
5367       This book and the code is based on libuv version v1.42.0.
5368
5369   Code
5370       All the example code and the source of the book is included as part  of
5371       the libuv project on GitHub.  Clone or Download libuv, then build it:
5372
5373          sh autogen.sh
5374          ./configure
5375          make
5376
5377       There is no need to make install. To build the examples run make in the
5378       docs/code/ directory.
5379
5380   Basics of libuv
5381       libuv enforces an asynchronous, event-driven style of programming.  Its
5382       core  job  is to provide an event loop and callback based notifications
5383       of I/O and other activities.  libuv offers core utilities like  timers,
5384       non-blocking networking support, asynchronous file system access, child
5385       processes and more.
5386
5387   Event loops
5388       In event-driven programming, an application expresses interest in  cer‐
5389       tain  events and respond to them when they occur. The responsibility of
5390       gathering events from the operating system or monitoring other  sources
5391       of  events  is handled by libuv, and the user can register callbacks to
5392       be invoked when an event occurs.  The event-loop usually keeps  running
5393       forever. In pseudocode:
5394
5395          while there are still events to process:
5396              e = get the next event
5397              if there is a callback associated with e:
5398                  call the callback
5399
5400       Some examples of events are:
5401
5402       • File is ready for writing
5403
5404       • A socket has data ready to be read
5405
5406       • A timer has timed out
5407
5408       This  event  loop  is  encapsulated by uv_run() -- the end-all function
5409       when using libuv.
5410
5411       The most common activity of systems programs is to deal with input  and
5412       output,  rather  than a lot of number-crunching. The problem with using
5413       conventional input/output functions (read, fprintf, etc.) is that  they
5414       are  blocking.  The  actual write to a hard disk or reading from a net‐
5415       work, takes a disproportionately long time compared to the speed of the
5416       processor.  The  functions don't return until the task is done, so that
5417       your program is doing nothing. For programs which require high  perfor‐
5418       mance this is a major roadblock as other activities and other I/O oper‐
5419       ations are kept waiting.
5420
5421       One of the standard solutions is to use threads. Each blocking I/O  op‐
5422       eration is started in a separate thread (or in a thread pool). When the
5423       blocking function gets invoked in the thread, the operating system  can
5424       schedule another thread to run, which actually needs the CPU.
5425
5426       The  approach  followed by libuv uses another style, which is the asyn‐
5427       chronous, non-blocking style. Most  modern  operating  systems  provide
5428       event  notification  subsystems.  For  example, a normal read call on a
5429       socket would block until the sender actually sent  something.  Instead,
5430       the  application  can  request the operating system to watch the socket
5431       and put an event notification in the queue. The application can inspect
5432       the  events at its convenience (perhaps doing some number crunching be‐
5433       fore to use the processor to the maximum) and  grab  the  data.  It  is
5434       asynchronous  because  the application expressed interest at one point,
5435       then used the data  at  another  point  (in  time  and  space).  It  is
5436       non-blocking  because  the  application  process  was  free to do other
5437       tasks.  This fits in well with libuv's event-loop approach,  since  the
5438       operating system events can be treated as just another libuv event. The
5439       non-blocking ensures that other events can continue to  be  handled  as
5440       fast as they come in [1].
5441
5442       NOTE:
5443          How  the I/O is run in the background is not of our concern, but due
5444          to the way our computer hardware works, with the thread as the basic
5445          unit  of  the  processor,  libuv  and  OSes  will  usually run back‐
5446          ground/worker  threads  and/or  polling  to  perform  tasks   in   a
5447          non-blocking manner.
5448
5449       Bert  Belder,  one  of  the libuv core developers has a small video ex‐
5450       plaining the architecture of libuv and its background. If you  have  no
5451       prior  experience  with  either  libuv  or libev, it is a quick, useful
5452       watch.
5453
5454       libuv's event loop is explained in more detail in the documentation.
5455
5456   Hello World
5457       With the basics out of the way, let's write our first libuv program. It
5458       does nothing, except start a loop which will exit immediately.
5459
5460       helloworld/main.c
5461
5462          #include <stdio.h>
5463          #include <stdlib.h>
5464          #include <uv.h>
5465
5466          int main() {
5467              uv_loop_t *loop = malloc(sizeof(uv_loop_t));
5468              uv_loop_init(loop);
5469
5470              printf("Now quitting.\n");
5471              uv_run(loop, UV_RUN_DEFAULT);
5472
5473              uv_loop_close(loop);
5474              free(loop);
5475              return 0;
5476          }
5477
5478
5479       This  program  quits immediately because it has no events to process. A
5480       libuv event loop has to be told to watch out for events using the vari‐
5481       ous API functions.
5482
5483       Starting  with  libuv  v1.0,  users  should allocate the memory for the
5484       loops before initializing it with uv_loop_init(uv_loop_t *).  This  al‐
5485       lows you to plug in custom memory management. Remember to de-initialize
5486       the loop using uv_loop_close(uv_loop_t *) and then delete the  storage.
5487       The  examples  never close loops since the program quits after the loop
5488       ends and the system will reclaim memory. Production grade projects, es‐
5489       pecially  long  running  systems  programs, should take care to release
5490       correctly.
5491
5492   Default loop
5493       A default loop is provided by libuv and can be  accessed  using  uv_de‐
5494       fault_loop(). You should use this loop if you only want a single loop.
5495
5496       default-loop/main.c
5497
5498          #include <stdio.h>
5499          #include <uv.h>
5500
5501          int main() {
5502              uv_loop_t *loop = uv_default_loop();
5503
5504              printf("Default loop.\n");
5505              uv_run(loop, UV_RUN_DEFAULT);
5506
5507              uv_loop_close(loop);
5508              return 0;
5509          }
5510
5511
5512       NOTE:
5513          node.js  uses  the default loop as its main loop. If you are writing
5514          bindings you should be aware of this.
5515
5516   Error handling
5517       Initialization functions or synchronous functions which may fail return
5518       a  negative  number on error. Async functions that may fail will pass a
5519       status parameter to their callbacks. The error messages are defined  as
5520       UV_E* constants.
5521
5522       You  can use the uv_strerror(int) and uv_err_name(int) functions to get
5523       a const char * describing the error or the error name respectively.
5524
5525       I/O read callbacks (such as for files and sockets) are passed a parame‐
5526       ter  nread.  If nread is less than 0, there was an error (UV_EOF is the
5527       end of file error, which you may want to handle differently).
5528
5529   Handles and Requests
5530       libuv works by the user expressing interest in particular events.  This
5531       is  usually  done  by  creating  a  handle  to  an I/O device, timer or
5532       process.  Handles are opaque structs named as uv_TYPE_t where type sig‐
5533       nifies what the handle is used for.
5534
5535       libuv watchers
5536
5537          /* Handle types. */
5538          typedef struct uv_loop_s uv_loop_t;
5539          typedef struct uv_handle_s uv_handle_t;
5540          typedef struct uv_dir_s uv_dir_t;
5541          typedef struct uv_stream_s uv_stream_t;
5542          typedef struct uv_tcp_s uv_tcp_t;
5543          typedef struct uv_udp_s uv_udp_t;
5544          typedef struct uv_pipe_s uv_pipe_t;
5545          typedef struct uv_tty_s uv_tty_t;
5546          typedef struct uv_poll_s uv_poll_t;
5547          typedef struct uv_timer_s uv_timer_t;
5548          typedef struct uv_prepare_s uv_prepare_t;
5549          typedef struct uv_check_s uv_check_t;
5550          typedef struct uv_idle_s uv_idle_t;
5551          typedef struct uv_async_s uv_async_t;
5552          typedef struct uv_process_s uv_process_t;
5553          typedef struct uv_fs_event_s uv_fs_event_t;
5554          typedef struct uv_fs_poll_s uv_fs_poll_t;
5555          typedef struct uv_signal_s uv_signal_t;
5556
5557          /* Request types. */
5558          typedef struct uv_req_s uv_req_t;
5559          typedef struct uv_getaddrinfo_s uv_getaddrinfo_t;
5560          typedef struct uv_getnameinfo_s uv_getnameinfo_t;
5561          typedef struct uv_shutdown_s uv_shutdown_t;
5562          typedef struct uv_write_s uv_write_t;
5563          typedef struct uv_connect_s uv_connect_t;
5564          typedef struct uv_udp_send_s uv_udp_send_t;
5565          typedef struct uv_fs_s uv_fs_t;
5566          typedef struct uv_work_s uv_work_t;
5567          typedef struct uv_random_s uv_random_t;
5568
5569          /* None of the above. */
5570          typedef struct uv_env_item_s uv_env_item_t;
5571          typedef struct uv_cpu_info_s uv_cpu_info_t;
5572          typedef struct uv_interface_address_s uv_interface_address_t;
5573          typedef struct uv_dirent_s uv_dirent_t;
5574          typedef struct uv_passwd_s uv_passwd_t;
5575          typedef struct uv_utsname_s uv_utsname_t;
5576          typedef struct uv_statfs_s uv_statfs_t;
5577
5578       Handles  represent long-lived objects. Async operations on such handles
5579       are identified using requests. A request is short-lived  (usually  used
5580       across  only one callback) and usually indicates one I/O operation on a
5581       handle.  Requests are used to preserve context between  the  initiation
5582       and  the  callback of individual actions. For example, an UDP socket is
5583       represented by a uv_udp_t, while individual writes to the socket use  a
5584       uv_udp_send_t  structure that is passed to the callback after the write
5585       is done.
5586
5587       Handles are setup by a corresponding:
5588
5589          uv_TYPE_init(uv_loop_t *, uv_TYPE_t *)
5590
5591       function.
5592
5593       Callbacks are functions which are called by libuv whenever an event the
5594       watcher  is  interested  in has taken place. Application specific logic
5595       will usually be  implemented  in  the  callback.  For  example,  an  IO
5596       watcher's  callback  will  receive  the  data read from a file, a timer
5597       callback will be triggered on timeout and so on.
5598
5599   Idling
5600       Here is an example of using an idle handle. The callback is called once
5601       on  every  turn  of the event loop. A use case for idle handles is dis‐
5602       cussed in Utilities. Let us use an idle watcher to look at the  watcher
5603       life  cycle  and  see  how uv_run() will now block because a watcher is
5604       present. The idle watcher is stopped when  the  count  is  reached  and
5605       uv_run() exits since no event watchers are active.
5606
5607       idle-basic/main.c
5608
5609          #include <stdio.h>
5610          #include <uv.h>
5611
5612          int64_t counter = 0;
5613
5614          void wait_for_a_while(uv_idle_t* handle) {
5615              counter++;
5616
5617              if (counter >= 10e6)
5618                  uv_idle_stop(handle);
5619          }
5620
5621          int main() {
5622              uv_idle_t idler;
5623
5624              uv_idle_init(uv_default_loop(), &idler);
5625              uv_idle_start(&idler, wait_for_a_while);
5626
5627              printf("Idling...\n");
5628              uv_run(uv_default_loop(), UV_RUN_DEFAULT);
5629
5630              uv_loop_close(uv_default_loop());
5631              return 0;
5632          }
5633
5634
5635   Storing context
5636       In  callback  based  programming  style  you'll often want to pass some
5637       'context' -- application specific information -- between the call  site
5638       and  the  callback.  All  handles and requests have a void* data member
5639       which you can set to the context and cast back in the callback. This is
5640       a  common  pattern used throughout the C library ecosystem. In addition
5641       uv_loop_t also has a similar data member.
5642
5643
5644                                        ----
5645
5646
5647
5648       [1]  Depending on the capacity of the hardware of course.
5649
5650   Filesystem
5651       Simple filesystem read/write is achieved using  the  uv_fs_*  functions
5652       and the uv_fs_t struct.
5653
5654       NOTE:
5655          The  libuv  filesystem  operations  are different from socket opera‐
5656          tions. Socket operations use the non-blocking operations provided by
5657          the  operating  system. Filesystem operations use blocking functions
5658          internally, but invoke these functions in a thread pool  and  notify
5659          watchers registered with the event loop when application interaction
5660          is required.
5661
5662       All filesystem functions have two forms - synchronous and asynchronous.
5663
5664       The synchronous forms automatically get called (and block) if the call‐
5665       back is null. The return value of functions is a libuv error code. This
5666       is usually only useful for synchronous calls.  The asynchronous form is
5667       called when a callback is passed and the return value is 0.
5668
5669   Reading/Writing files
5670       A file descriptor is obtained using
5671
5672          int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb)
5673
5674       flags and mode are standard Unix flags.  libuv takes care of converting
5675       to the appropriate Windows flags.
5676
5677       File descriptors are closed using
5678
5679          int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb)
5680
5681       Filesystem operation callbacks have the signature:
5682
5683          void callback(uv_fs_t* req);
5684
5685       Let's see a simple implementation of cat. We start with  registering  a
5686       callback for when the file is opened:
5687
5688       uvcat/main.c - opening a file
5689
5690              // The request passed to the callback is the same as the one the call setup
5691              // function was passed.
5692              assert(req == &open_req);
5693              if (req->result >= 0) {
5694                  iov = uv_buf_init(buffer, sizeof(buffer));
5695                  uv_fs_read(uv_default_loop(), &read_req, req->result,
5696                             &iov, 1, -1, on_read);
5697              }
5698              else {
5699                  fprintf(stderr, "error opening file: %s\n", uv_strerror((int)req->result));
5700              }
5701          }
5702
5703
5704
5705       The  result  field  of  a uv_fs_t is the file descriptor in case of the
5706       uv_fs_open callback. If the file is successfully opened, we start read‐
5707       ing it.
5708
5709       uvcat/main.c - read callback
5710
5711              if (req->result < 0) {
5712                  fprintf(stderr, "Read error: %s\n", uv_strerror(req->result));
5713              }
5714              else if (req->result == 0) {
5715                  uv_fs_t close_req;
5716                  // synchronous
5717                  uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
5718              }
5719              else if (req->result > 0) {
5720                  iov.len = req->result;
5721                  uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write);
5722              }
5723          }
5724
5725
5726
5727       In the case of a read call, you should pass an initialized buffer which
5728       will be filled with data before the read  callback  is  triggered.  The
5729       uv_fs_*  operations  map almost directly to certain POSIX functions, so
5730       EOF is indicated in this case by result being 0. In the case of streams
5731       or  pipes,  the  UV_EOF constant would have been passed as a status in‐
5732       stead.
5733
5734       Here you see a common pattern when writing asynchronous  programs.  The
5735       uv_fs_close()  call is performed synchronously. Usually tasks which are
5736       one-off, or are done as part of the startup or shutdown stage are  per‐
5737       formed synchronously, since we are interested in fast I/O when the pro‐
5738       gram is going about its primary task  and  dealing  with  multiple  I/O
5739       sources.  For solo tasks the performance difference usually is negligi‐
5740       ble and may lead to simpler code.
5741
5742       Filesystem writing is similarly simple using uv_fs_write().  Your call‐
5743       back  will  be  triggered after the write is complete.  In our case the
5744       callback simply drives the next read. Thus read and  write  proceed  in
5745       lockstep via callbacks.
5746
5747       uvcat/main.c - write callback
5748
5749              if (req->result < 0) {
5750                  fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result));
5751              }
5752              else {
5753                  uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read);
5754              }
5755          }
5756
5757
5758
5759       WARNING:
5760          Due  to  the way filesystems and disk drives are configured for per‐
5761          formance, a write that 'succeeds' may not be committed to disk yet.
5762
5763       We set the dominos rolling in main():
5764
5765       uvcat/main.c
5766
5767              uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open);
5768              uv_run(uv_default_loop(), UV_RUN_DEFAULT);
5769
5770              uv_fs_req_cleanup(&open_req);
5771              uv_fs_req_cleanup(&read_req);
5772              uv_fs_req_cleanup(&write_req);
5773              return 0;
5774          }
5775
5776
5777       WARNING:
5778          The uv_fs_req_cleanup() function must always be called on filesystem
5779          requests to free internal memory allocations in libuv.
5780
5781   Filesystem operations
5782       All  the  standard  filesystem  operations like unlink, rmdir, stat are
5783       supported asynchronously and have intuitive argument order. They follow
5784       the same patterns as the read/write/open calls, returning the result in
5785       the uv_fs_t.result field. The full list:
5786
5787       Filesystem operations
5788
5789          int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb);
5790          int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb);
5791          int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb);
5792          int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5793          int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb);
5794          int uv_fs_copyfile(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb);
5795          int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb);
5796          int uv_fs_mkdtemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb);
5797          int uv_fs_mkstemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb);
5798          int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5799          int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, uv_fs_cb cb);
5800          int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent);
5801          int uv_fs_opendir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5802          int uv_fs_readdir(uv_loop_t* loop, uv_fs_t* req, uv_dir_t* dir, uv_fs_cb cb);
5803          int uv_fs_closedir(uv_loop_t* loop, uv_fs_t* req, uv_dir_t* dir, uv_fs_cb cb);
5804          int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5805          int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb);
5806          int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb);
5807          int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb);
5808          int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb);
5809          int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file file, int64_t offset, uv_fs_cb cb);
5810          int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb);
5811          int uv_fs_access(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb);
5812          int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb);
5813          int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb);
5814          int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file file, double atime, double mtime, uv_fs_cb cb);
5815          int uv_fs_lutime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb);
5816          int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5817          int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb);
5818          int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb);
5819          int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5820          int uv_fs_realpath(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5821          int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file file, int mode, uv_fs_cb cb);
5822          int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb);
5823          int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb);
5824          int uv_fs_lchown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb);
5825          int uv_fs_statfs(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
5826
5827   Buffers and Streams
5828       The basic I/O handle in libuv is the stream (uv_stream_t). TCP sockets,
5829       UDP  sockets,  and pipes for file I/O and IPC are all treated as stream
5830       subclasses.
5831
5832       Streams are initialized using custom functions for each subclass,  then
5833       operated upon using
5834
5835          int uv_read_start(uv_stream_t*, uv_alloc_cb alloc_cb, uv_read_cb read_cb);
5836          int uv_read_stop(uv_stream_t*);
5837          int uv_write(uv_write_t* req, uv_stream_t* handle,
5838                       const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb);
5839
5840       The  stream based functions are simpler to use than the filesystem ones
5841       and  libuv  will  automatically  keep  reading  from  a   stream   when
5842       uv_read_start() is called once, until uv_read_stop() is called.
5843
5844       The  discrete  unit of data is the buffer -- uv_buf_t. This is simply a
5845       collection of  a  pointer  to  bytes  (uv_buf_t.base)  and  the  length
5846       (uv_buf_t.len). The uv_buf_t is lightweight and passed around by value.
5847       What does require management is the actual bytes, which have to be  al‐
5848       located and freed by the application.
5849
5850       ERROR:
5851          THIS PROGRAM DOES NOT ALWAYS WORK, NEED SOMETHING BETTER
5852
5853       To  demonstrate  streams  we  will  need  to use uv_pipe_t. This allows
5854       streaming local files [2]. Here is a simple tee  utility  using  libuv.
5855       Doing all operations asynchronously shows the power of evented I/O. The
5856       two writes won't block each other, but we have to be  careful  to  copy
5857       over the buffer data to ensure we don't free a buffer until it has been
5858       written.
5859
5860       The program is to be executed as:
5861
5862          ./uvtee <output_file>
5863
5864       We start off opening pipes on the files we require. libuv  pipes  to  a
5865       file are opened as bidirectional by default.
5866
5867       uvtee/main.c - read on pipes
5868
5869              loop = uv_default_loop();
5870
5871              uv_pipe_init(loop, &stdin_pipe, 0);
5872              uv_pipe_open(&stdin_pipe, 0);
5873
5874              uv_pipe_init(loop, &stdout_pipe, 0);
5875              uv_pipe_open(&stdout_pipe, 1);
5876
5877              uv_fs_t file_req;
5878              int fd = uv_fs_open(loop, &file_req, argv[1], O_CREAT | O_RDWR, 0644, NULL);
5879              uv_pipe_init(loop, &file_pipe, 0);
5880              uv_pipe_open(&file_pipe, fd);
5881
5882              uv_read_start((uv_stream_t*)&stdin_pipe, alloc_buffer, read_stdin);
5883
5884              uv_run(loop, UV_RUN_DEFAULT);
5885              return 0;
5886          }
5887
5888
5889       The  third  argument of uv_pipe_init() should be set to 1 for IPC using
5890       named pipes. This is covered in Processes. The uv_pipe_open() call  as‐
5891       sociates  the  pipe  with the file descriptor, in this case 0 (standard
5892       input).
5893
5894       We start monitoring stdin. The alloc_buffer callback is invoked as  new
5895       buffers  are  required to hold incoming data. read_stdin will be called
5896       with these buffers.
5897
5898       uvtee/main.c - reading buffers
5899
5900              *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size);
5901          }
5902
5903          void free_write_req(uv_write_t *req) {
5904              if (nread < 0){
5905                  if (nread == UV_EOF){
5906                      // end of file
5907                      uv_close((uv_handle_t *)&stdin_pipe, NULL);
5908                      uv_close((uv_handle_t *)&stdout_pipe, NULL);
5909                      uv_close((uv_handle_t *)&file_pipe, NULL);
5910                  }
5911              } else if (nread > 0) {
5912                  write_data((uv_stream_t *)&stdout_pipe, nread, *buf, on_stdout_write);
5913                  write_data((uv_stream_t *)&file_pipe, nread, *buf, on_file_write);
5914              }
5915
5916              // OK to free buffer as write_data copies it.
5917              if (buf->base)
5918                  free(buf->base);
5919          }
5920
5921
5922
5923       The standard malloc is sufficient here, but you can use any memory  al‐
5924       location scheme. For example, node.js uses its own slab allocator which
5925       associates buffers with V8 objects.
5926
5927       The read callback nread parameter is less than 0 on any error. This er‐
5928       ror  might  be  EOF,  in which case we close all the streams, using the
5929       generic close function uv_close() which deals with the handle based  on
5930       its internal type.  Otherwise nread is a non-negative number and we can
5931       attempt to write that many bytes to the output streams. Finally  remem‐
5932       ber that buffer allocation and deallocation is application responsibil‐
5933       ity, so we free the data.
5934
5935       The allocation callback may return a buffer  with  length  zero  if  it
5936       fails  to  allocate  memory. In this case, the read callback is invoked
5937       with error UV_ENOBUFS. libuv will  continue  to  attempt  to  read  the
5938       stream  though,  so  you must explicitly call uv_close() if you want to
5939       stop when allocation fails.
5940
5941       The read callback may be called with nread = 0, indicating that at this
5942       point  there  is nothing to be read. Most applications will just ignore
5943       this.
5944
5945       uvtee/main.c - Write to pipe
5946
5947              uv_write_t req;
5948              uv_buf_t buf;
5949          } write_req_t;
5950
5951          uv_loop_t *loop;
5952              write_req_t *wr = (write_req_t*) req;
5953              free(wr->buf.base);
5954              free(wr);
5955          }
5956
5957          void on_stdout_write(uv_write_t *req, int status) {
5958              free_write_req(req);
5959          }
5960
5961          void on_file_write(uv_write_t *req, int status) {
5962              free_write_req(req);
5963          }
5964
5965          void write_data(uv_stream_t *dest, size_t size, uv_buf_t buf, uv_write_cb cb) {
5966              write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t));
5967              req->buf = uv_buf_init((char*) malloc(size), size);
5968              memcpy(req->buf.base, buf.base, size);
5969              uv_write((uv_write_t*) req, (uv_stream_t*)dest, &req->buf, 1, cb);
5970          }
5971
5972
5973
5974       write_data() makes a copy of the buffer obtained from read. This buffer
5975       does not get passed through to the write callback trigged on write com‐
5976       pletion. To get around this we wrap a write request  and  a  buffer  in
5977       write_req_t  and  unwrap  it in the callbacks. We make a copy so we can
5978       free the two buffers from the two calls to write_data independently  of
5979       each other. While acceptable for a demo program like this, you'll prob‐
5980       ably want smarter memory management, like reference counted buffers  or
5981       a pool of buffers in any major application.
5982
5983       WARNING:
5984          If your program is meant to be used with other programs it may know‐
5985          ingly or unknowingly be writing to a pipe. This makes it susceptible
5986          to aborting on receiving a SIGPIPE. It is a good idea to insert:
5987
5988              signal(SIGPIPE, SIG_IGN)
5989
5990          in the initialization stages of your application.
5991
5992   File change events
5993       All  modern operating systems provide APIs to put watches on individual
5994       files or directories and be informed when the files are modified. libuv
5995       wraps common file change notification libraries [1]. This is one of the
5996       more inconsistent parts of libuv. File change notification systems  are
5997       themselves  extremely  varied  across  platforms  so getting everything
5998       working everywhere is difficult. To demonstrate, I'm going to  build  a
5999       simple  utility  which runs a command whenever any of the watched files
6000       change:
6001
6002          ./onchange <command> <file1> [file2] ...
6003
6004       NOTE:
6005          Currently this example only works on OSX and Windows.  Refer to  the
6006          notes of uv_fs_event_start function.
6007
6008       The file change notification is started using uv_fs_event_init():
6009
6010       onchange/main.c - The setup
6011
6012          int main(int argc, char **argv) {
6013              if (argc <= 2) {
6014                  fprintf(stderr, "Usage: %s <command> <file1> [file2 ...]\n", argv[0]);
6015                  return 1;
6016              }
6017
6018              loop = uv_default_loop();
6019              command = argv[1];
6020
6021              while (argc-- > 2) {
6022                  fprintf(stderr, "Adding watch on %s\n", argv[argc]);
6023                  uv_fs_event_t *fs_event_req = malloc(sizeof(uv_fs_event_t));
6024                  uv_fs_event_init(loop, fs_event_req);
6025                  // The recursive flag watches subdirectories too.
6026                  uv_fs_event_start(fs_event_req, run_command, argv[argc], UV_FS_EVENT_RECURSIVE);
6027              }
6028
6029              return uv_run(loop, UV_RUN_DEFAULT);
6030          }
6031
6032
6033       The third argument is the actual file or directory to monitor. The last
6034       argument, flags, can be:
6035
6036          /*
6037           * Flags to be passed to uv_fs_event_start().
6038           */
6039          enum uv_fs_event_flags {
6040              UV_FS_EVENT_WATCH_ENTRY = 1,
6041              UV_FS_EVENT_STAT = 2,
6042              UV_FS_EVENT_RECURSIVE = 4
6043          };
6044
6045       UV_FS_EVENT_WATCH_ENTRY and UV_FS_EVENT_STAT don't do  anything  (yet).
6046       UV_FS_EVENT_RECURSIVE  will  start  watching  subdirectories as well on
6047       supported platforms.
6048
6049       The callback will receive the following arguments:
6050
6051          1. uv_fs_event_t *handle - The handle. The path field of the  handle
6052             is the file on which the watch was set.
6053
6054          2. const char *filename - If a directory is being monitored, this is
6055             the file which was changed. Only non-null on Linux  and  Windows.
6056             May be null even on those platforms.
6057
6058          3. int  events  -  one of UV_RENAME or UV_CHANGE, or a bitwise OR of
6059             both.
6060
6061          4. int status - If status < 0, there is an libuv error.
6062
6063       In our example we simply print the arguments and run the command  using
6064       system().
6065
6066       onchange/main.c - file change notification callback
6067
6068          void run_command(uv_fs_event_t *handle, const char *filename, int events, int status) {
6069              char path[1024];
6070              size_t size = 1023;
6071              // Does not handle error if path is longer than 1023.
6072              uv_fs_event_getpath(handle, path, &size);
6073              path[size] = '\0';
6074
6075              fprintf(stderr, "Change detected in %s: ", path);
6076              if (events & UV_RENAME)
6077                  fprintf(stderr, "renamed");
6078              if (events & UV_CHANGE)
6079                  fprintf(stderr, "changed");
6080
6081              fprintf(stderr, " %s\n", filename ? filename : "");
6082              system(command);
6083          }
6084
6085
6086
6087                                        ----
6088
6089
6090
6091       [1]  inotify on Linux, FSEvents on Darwin, kqueue on BSDs, ReadDirecto‐
6092            ryChangesW on Windows, event ports on Solaris, unsupported on Cyg‐
6093            win
6094
6095       [2]  see Parent-child IPC
6096
6097   Networking
6098       Networking  in  libuv is not much different from directly using the BSD
6099       socket interface, some things are easier, all are non-blocking, but the
6100       concepts  stay  the same. In addition libuv offers utility functions to
6101       abstract the annoying, repetitive and low-level tasks like  setting  up
6102       sockets using the BSD socket structures, DNS lookup, and tweaking vari‐
6103       ous socket parameters.
6104
6105       The uv_tcp_t and uv_udp_t structures are used for network I/O.
6106
6107       NOTE:
6108          The code samples in this chapter exist to show certain  libuv  APIs.
6109          They  are  not  examples  of good quality code. They leak memory and
6110          don't always close connections properly.
6111
6112   TCP
6113       TCP is a connection oriented, stream protocol and is therefore based on
6114       the libuv streams infrastructure.
6115
6116   Server
6117       Server sockets proceed by:
6118
6119       1. uv_tcp_init the TCP handle.
6120
6121       2. uv_tcp_bind it.
6122
6123       3. Call  uv_listen  on the handle to have a callback invoked whenever a
6124          new connection is established by a client.
6125
6126       4. Use uv_accept to accept the connection.
6127
6128       5. Use stream operations to communicate with the client.
6129
6130       Here is a simple echo server
6131
6132       tcp-echo-server/main.c - The listen socket
6133
6134                  uv_close((uv_handle_t*) client, on_close);
6135              }
6136          }
6137
6138          int main() {
6139              loop = uv_default_loop();
6140
6141              uv_tcp_t server;
6142              uv_tcp_init(loop, &server);
6143
6144              uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr);
6145
6146              uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
6147              int r = uv_listen((uv_stream_t*) &server, DEFAULT_BACKLOG, on_new_connection);
6148              if (r) {
6149                  fprintf(stderr, "Listen error %s\n", uv_strerror(r));
6150                  return 1;
6151              }
6152              return uv_run(loop, UV_RUN_DEFAULT);
6153          }
6154
6155
6156       You can see the utility function uv_ip4_addr being used to convert from
6157       a human readable IP address, port pair to the sockaddr_in structure re‐
6158       quired by the BSD socket  APIs.  The  reverse  can  be  obtained  using
6159       uv_ip4_name.
6160
6161       NOTE:
6162          There are uv_ip6_* analogues for the ip4 functions.
6163
6164       Most  of  the setup functions are synchronous since they are CPU-bound.
6165       uv_listen is where we return to libuv's callback style. The second  ar‐
6166       guments  is  the  backlog queue -- the maximum length of queued connec‐
6167       tions.
6168
6169       When a connection is initiated by clients, the callback is required  to
6170       set  up  a  handle for the client socket and associate the handle using
6171       uv_accept.  In this case we also establish  interest  in  reading  from
6172       this stream.
6173
6174       tcp-echo-server/main.c - Accepting the client
6175
6176
6177              free(buf->base);
6178          }
6179
6180          void on_new_connection(uv_stream_t *server, int status) {
6181              if (status < 0) {
6182                  fprintf(stderr, "New connection error %s\n", uv_strerror(status));
6183                  // error!
6184                  return;
6185              }
6186
6187              uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
6188              uv_tcp_init(loop, client);
6189              if (uv_accept(server, (uv_stream_t*) client) == 0) {
6190                  uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
6191              }
6192
6193
6194       The  remaining  set of functions is very similar to the streams example
6195       and can be found in the code. Just remember to call uv_close  when  the
6196       socket  isn't required. This can be done even in the uv_listen callback
6197       if you are not interested in accepting the connection.
6198
6199   Client
6200       Where you do bind/listen/accept on the server, on the client side  it's
6201       simply a matter of calling uv_tcp_connect. The same uv_connect_cb style
6202       callback of uv_listen is used by uv_tcp_connect. Try:
6203
6204          uv_tcp_t* socket = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
6205          uv_tcp_init(loop, socket);
6206
6207          uv_connect_t* connect = (uv_connect_t*)malloc(sizeof(uv_connect_t));
6208
6209          struct sockaddr_in dest;
6210          uv_ip4_addr("127.0.0.1", 80, &dest);
6211
6212          uv_tcp_connect(connect, socket, (const struct sockaddr*)&dest, on_connect);
6213
6214       where on_connect will be called after the  connection  is  established.
6215       The callback receives the uv_connect_t struct, which has a member .han‐
6216       dle pointing to the socket.
6217
6218   UDP
6219       The User Datagram Protocol offers  connectionless,  unreliable  network
6220       communication.  Hence  libuv doesn't offer a stream. Instead libuv pro‐
6221       vides non-blocking UDP support via the uv_udp_t handle (for  receiving)
6222       and  uv_udp_send_t  request  (for  sending) and related functions. That
6223       said, the actual API for reading/writing  is  very  similar  to  normal
6224       stream  reads.  To  look  at how UDP can be used, the example shows the
6225       first stage of obtaining an IP address from a DHCP server -- DHCP  Dis‐
6226       cover.
6227
6228       NOTE:
6229          You  will have to run udp-dhcp as root since it uses well known port
6230          numbers below 1024.
6231
6232       udp-dhcp/main.c - Setup and send UDP packets
6233
6234
6235          uv_loop_t *loop;
6236          uv_udp_t send_socket;
6237          uv_udp_t recv_socket;
6238
6239
6240          int main() {
6241              loop = uv_default_loop();
6242
6243              uv_udp_init(loop, &recv_socket);
6244              struct sockaddr_in recv_addr;
6245              uv_ip4_addr("0.0.0.0", 68, &recv_addr);
6246              uv_udp_bind(&recv_socket, (const struct sockaddr *)&recv_addr, UV_UDP_REUSEADDR);
6247              uv_udp_recv_start(&recv_socket, alloc_buffer, on_read);
6248
6249              uv_udp_init(loop, &send_socket);
6250              struct sockaddr_in broadcast_addr;
6251              uv_ip4_addr("0.0.0.0", 0, &broadcast_addr);
6252              uv_udp_bind(&send_socket, (const struct sockaddr *)&broadcast_addr, 0);
6253              uv_udp_set_broadcast(&send_socket, 1);
6254
6255              uv_udp_send_t send_req;
6256              uv_buf_t discover_msg = make_discover_msg();
6257
6258              struct sockaddr_in send_addr;
6259              uv_ip4_addr("255.255.255.255", 67, &send_addr);
6260              uv_udp_send(&send_req, &send_socket, &discover_msg, 1, (const struct sockaddr *)&send_addr, on_send);
6261
6262              return uv_run(loop, UV_RUN_DEFAULT);
6263          }
6264
6265
6266       NOTE:
6267          The IP address 0.0.0.0 is used to bind to all interfaces. The IP ad‐
6268          dress  255.255.255.255  is  a broadcast address meaning that packets
6269          will be sent to all interfaces on the subnet.  port 0 means that the
6270          OS randomly assigns a port.
6271
6272       First  we  setup the receiving socket to bind on all interfaces on port
6273       68 (DHCP client) and start a read on it. This will read back  responses
6274       from  any DHCP server that replies. We use the UV_UDP_REUSEADDR flag to
6275       play nice with any other system DHCP clients that are running  on  this
6276       computer on the same port.  Then we setup a similar send socket and use
6277       uv_udp_send to send a broadcast message on port 67 (DHCP server).
6278
6279       It is necessary to set the broadcast flag, otherwise you  will  get  an
6280       EACCES  error [1]. The exact message being sent is not relevant to this
6281       book and you can study the code if you are  interested.  As  usual  the
6282       read and write callbacks will receive a status code of < 0 if something
6283       went wrong.
6284
6285       Since UDP sockets are not connected to  a  particular  peer,  the  read
6286       callback receives an extra parameter about the sender of the packet.
6287
6288       nread may be zero if there is no more data to be read. If addr is NULL,
6289       it indicates there is nothing to read (the callback shouldn't  do  any‐
6290       thing),  if  not NULL, it indicates that an empty datagram was received
6291       from the host at addr. The flags parameter may be UV_UDP_PARTIAL if the
6292       buffer  provided  by  your  allocator  was not large enough to hold the
6293       data. In this case the OS will discard the  data  that  could  not  fit
6294       (That's UDP for you!).
6295
6296       udp-dhcp/main.c - Reading packets
6297
6298          void on_read(uv_udp_t *req, ssize_t nread, const uv_buf_t *buf, const struct sockaddr *addr, unsigned flags) {
6299              if (nread < 0) {
6300                  fprintf(stderr, "Read error %s\n", uv_err_name(nread));
6301                  uv_close((uv_handle_t*) req, NULL);
6302                  free(buf->base);
6303                  return;
6304              }
6305
6306              char sender[17] = { 0 };
6307              uv_ip4_name((const struct sockaddr_in*) addr, sender, 16);
6308              fprintf(stderr, "Recv from %s\n", sender);
6309
6310              // ... DHCP specific code
6311              unsigned int *as_integer = (unsigned int*)buf->base;
6312              unsigned int ipbin = ntohl(as_integer[4]);
6313              unsigned char ip[4] = {0};
6314              int i;
6315              for (i = 0; i < 4; i++)
6316                  ip[i] = (ipbin >> i*8) & 0xff;
6317              fprintf(stderr, "Offered IP %d.%d.%d.%d\n", ip[3], ip[2], ip[1], ip[0]);
6318
6319              free(buf->base);
6320              uv_udp_recv_stop(req);
6321          }
6322
6323
6324   UDP Options
6325   Time-to-live
6326       The   TTL   of  packets  sent  on  the  socket  can  be  changed  using
6327       uv_udp_set_ttl.
6328
6329   IPv6 stack only
6330       IPv6 sockets can be used for both IPv4 and IPv6 communication.  If  you
6331       want to restrict the socket to IPv6 only, pass the UV_UDP_IPV6ONLY flag
6332       to uv_udp_bind.
6333
6334   Multicast
6335       A socket can (un)subscribe to a multicast group using:
6336
6337       where membership is UV_JOIN_GROUP or UV_LEAVE_GROUP.
6338
6339       The concepts of multicasting are nicely explained in this guide.
6340
6341       Local loopback of multicast packets is  enabled  by  default  [2],  use
6342       uv_udp_set_multicast_loop to switch it off.
6343
6344       The  packet  time-to-live  for  multicast  packets can be changed using
6345       uv_udp_set_multicast_ttl.
6346
6347   Querying DNS
6348       libuv provides asynchronous DNS resolution. For this  it  provides  its
6349       own getaddrinfo replacement [3]. In the callback you can perform normal
6350       socket operations on the retrieved addresses.  Let's  connect  to  Lib‐
6351       era.chat to see an example of DNS resolution.
6352
6353       dns/main.c
6354
6355
6356          int main() {
6357              loop = uv_default_loop();
6358
6359              struct addrinfo hints;
6360              hints.ai_family = PF_INET;
6361              hints.ai_socktype = SOCK_STREAM;
6362              hints.ai_protocol = IPPROTO_TCP;
6363              hints.ai_flags = 0;
6364
6365              uv_getaddrinfo_t resolver;
6366              fprintf(stderr, "irc.libera.chat is... ");
6367              int r = uv_getaddrinfo(loop, &resolver, on_resolved, "irc.libera.chat", "6667", &hints);
6368
6369              if (r) {
6370                  fprintf(stderr, "getaddrinfo call error %s\n", uv_err_name(r));
6371                  return 1;
6372              }
6373              return uv_run(loop, UV_RUN_DEFAULT);
6374          }
6375
6376
6377       If  uv_getaddrinfo  returns non-zero, something went wrong in the setup
6378       and your callback won't be invoked at all. All arguments can  be  freed
6379       immediately  after  uv_getaddrinfo  returns. The hostname, servname and
6380       hints structures are documented in the getaddrinfo man page. The  call‐
6381       back can be NULL in which case the function will run synchronously.
6382
6383       In  the  resolver callback, you can pick any IP from the linked list of
6384       struct addrinfo(s). This also demonstrates uv_tcp_connect. It is neces‐
6385       sary to call uv_freeaddrinfo in the callback.
6386
6387       dns/main.c
6388
6389
6390          void on_resolved(uv_getaddrinfo_t *resolver, int status, struct addrinfo *res) {
6391              if (status < 0) {
6392                  fprintf(stderr, "getaddrinfo callback error %s\n", uv_err_name(status));
6393                  return;
6394              }
6395
6396              char addr[17] = {'\0'};
6397              uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16);
6398              fprintf(stderr, "%s\n", addr);
6399
6400              uv_connect_t *connect_req = (uv_connect_t*) malloc(sizeof(uv_connect_t));
6401              uv_tcp_t *socket = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
6402              uv_tcp_init(loop, socket);
6403
6404              uv_tcp_connect(connect_req, socket, (const struct sockaddr*) res->ai_addr, on_connect);
6405
6406              uv_freeaddrinfo(res);
6407          }
6408
6409
6410       libuv also provides the inverse uv_getnameinfo.
6411
6412   Network interfaces
6413       Information  about  the  system's  network  interfaces  can be obtained
6414       through libuv using uv_interface_addresses. This  simple  program  just
6415       prints  out  all the interface details so you get an idea of the fields
6416       that are available. This is useful to allow your service to bind to  IP
6417       addresses when it starts.
6418
6419       interfaces/main.c
6420
6421          #include <stdio.h>
6422          #include <uv.h>
6423
6424          int main() {
6425              char buf[512];
6426              uv_interface_address_t *info;
6427              int count, i;
6428
6429              uv_interface_addresses(&info, &count);
6430              i = count;
6431
6432              printf("Number of interfaces: %d\n", count);
6433              while (i--) {
6434                  uv_interface_address_t interface_a = info[i];
6435
6436                  printf("Name: %s\n", interface_a.name);
6437                  printf("Internal? %s\n", interface_a.is_internal ? "Yes" : "No");
6438
6439                  if (interface_a.address.address4.sin_family == AF_INET) {
6440                      uv_ip4_name(&interface_a.address.address4, buf, sizeof(buf));
6441                      printf("IPv4 address: %s\n", buf);
6442                  }
6443                  else if (interface_a.address.address4.sin_family == AF_INET6) {
6444                      uv_ip6_name(&interface_a.address.address6, buf, sizeof(buf));
6445                      printf("IPv6 address: %s\n", buf);
6446                  }
6447
6448                  printf("\n");
6449              }
6450
6451              uv_free_interface_addresses(info, count);
6452              return 0;
6453          }
6454
6455
6456       is_internal  is  true  for loopback interfaces. Note that if a physical
6457       interface has multiple IPv4/IPv6 addresses, the name will  be  reported
6458       multiple times, with each address being reported once.
6459
6460
6461                                        ----
6462
6463
6464
6465       [1]  https://beej.us/guide/bgnet/html/#broadcast-packetshello-world
6466
6467       [2]  https://www.tldp.org/HOWTO/Multicast-HOWTO-6.html#ss6.1
6468
6469       [3]  libuv  use  the  system getaddrinfo in the libuv threadpool. libuv
6470            v0.8.0 and earlier also included c-ares  as  an  alternative,  but
6471            this has been removed in v0.9.0.
6472
6473   Threads
6474       Wait a minute? Why are we on threads? Aren't event loops supposed to be
6475       the way to do web-scale programming? Well... no. Threads are still  the
6476       medium  in which processors do their jobs. Threads are therefore mighty
6477       useful sometimes, even though you might have to  wade  through  various
6478       synchronization primitives.
6479
6480       Threads  are  used internally to fake the asynchronous nature of all of
6481       the system calls. libuv also uses threads to allow  you,  the  applica‐
6482       tion,  to  perform  a task asynchronously that is actually blocking, by
6483       spawning a thread and collecting the result when it is done.
6484
6485       Today there are two predominant thread libraries: the  Windows  threads
6486       implementation and POSIX's pthreads(7). libuv's thread API is analogous
6487       to the pthreads API and often has similar semantics.
6488
6489       A notable aspect of libuv's thread facilities is that it is a self con‐
6490       tained  section  within libuv. Whereas other features intimately depend
6491       on the event loop and callback principles, threads are complete  agnos‐
6492       tic,  they block as required, signal errors directly via return values,
6493       and, as shown in the first example, don't even require a running  event
6494       loop.
6495
6496       libuv's  thread API is also very limited since the semantics and syntax
6497       of threads are different on all platforms,  with  different  levels  of
6498       completeness.
6499
6500       This  chapter  makes  the following assumption: There is only one event
6501       loop, running in one thread (the main thread). No other  thread  inter‐
6502       acts with the event loop (except using uv_async_send).
6503
6504   Core thread operations
6505       There isn't much here, you just start a thread using uv_thread_create()
6506       and wait for it to close using uv_thread_join().
6507
6508       thread-create/main.c
6509
6510              int tracklen = 10;
6511              uv_thread_t hare_id;
6512              uv_thread_t tortoise_id;
6513              uv_thread_create(&hare_id, hare, &tracklen);
6514              uv_thread_create(&tortoise_id, tortoise, &tracklen);
6515
6516              uv_thread_join(&hare_id);
6517              uv_thread_join(&tortoise_id);
6518              return 0;
6519          }
6520
6521
6522       TIP:
6523          uv_thread_t is just an alias for pthread_t on Unix, but this  is  an
6524          implementation detail, avoid depending on it to always be true.
6525
6526       The  second  parameter  is  the  function which will serve as the entry
6527       point for the thread, the last parameter is a void * argument which can
6528       be used to pass custom parameters to the thread. The function hare will
6529       now run in a separate thread, scheduled pre-emptively by the  operating
6530       system:
6531
6532       thread-create/main.c
6533
6534              int tracklen = *((int *) arg);
6535              while (tracklen) {
6536                  tracklen--;
6537                  uv_sleep(1000);
6538                  fprintf(stderr, "Hare ran another step\n");
6539              }
6540              fprintf(stderr, "Hare done running!\n");
6541          }
6542
6543
6544
6545       Unlike  pthread_join()  which  allows  the target thread to pass back a
6546       value to the calling thread using a second parameter,  uv_thread_join()
6547       does not. To send values use Inter-thread communication.
6548
6549   Synchronization Primitives
6550       This section is purposely spartan. This book is not about threads, so I
6551       only catalogue any surprises in the libuv APIs here. For the  rest  you
6552       can look at the pthreads(7) man pages.
6553
6554   Mutexes
6555       The mutex functions are a direct map to the pthread equivalents.
6556
6557       libuv mutex functions
6558
6559          int uv_mutex_init(uv_mutex_t* handle);
6560          int uv_mutex_init_recursive(uv_mutex_t* handle);
6561          void uv_mutex_destroy(uv_mutex_t* handle);
6562          void uv_mutex_lock(uv_mutex_t* handle);
6563          int uv_mutex_trylock(uv_mutex_t* handle);
6564          void uv_mutex_unlock(uv_mutex_t* handle);
6565
6566       The  uv_mutex_init(),  uv_mutex_init_recursive() and uv_mutex_trylock()
6567       functions will return 0 on success, and an error code otherwise.
6568
6569       If libuv has been compiled with debugging enabled,  uv_mutex_destroy(),
6570       uv_mutex_lock() and uv_mutex_unlock() will abort() on error.  Similarly
6571       uv_mutex_trylock() will abort if the error is anything other  than  EA‐
6572       GAIN or EBUSY.
6573
6574       Recursive mutexes are supported, but you should not rely on them. Also,
6575       they should not be used with uv_cond_t variables.
6576
6577       The default BSD mutex implementation will raise an error  if  a  thread
6578       which has locked a mutex attempts to lock it again. For example, a con‐
6579       struct like:
6580
6581          uv_mutex_init(a_mutex);
6582          uv_mutex_lock(a_mutex);
6583          uv_thread_create(thread_id, entry, (void *)a_mutex);
6584          uv_mutex_lock(a_mutex);
6585          // more things here
6586
6587       can be used to wait until another thread  initializes  some  stuff  and
6588       then unlocks a_mutex but will lead to your program crashing if in debug
6589       mode, or return an error in the second call to uv_mutex_lock().
6590
6591       NOTE:
6592          Mutexes on Windows are always recursive.
6593
6594   Locks
6595       Read-write locks are a more granular access mechanism. Two readers  can
6596       access  shared  memory  at  the same time. A writer may not acquire the
6597       lock when it is held by a reader. A reader or writer may not acquire  a
6598       lock  when a writer is holding it. Read-write locks are frequently used
6599       in databases. Here is a toy example.
6600
6601       locks/main.c - simple rwlocks
6602
6603          #include <stdio.h>
6604          #include <uv.h>
6605
6606          uv_barrier_t blocker;
6607          uv_rwlock_t numlock;
6608          int shared_num;
6609
6610          void reader(void *n)
6611          {
6612              int num = *(int *)n;
6613              int i;
6614              for (i = 0; i < 20; i++) {
6615                  uv_rwlock_rdlock(&numlock);
6616                  printf("Reader %d: acquired lock\n", num);
6617                  printf("Reader %d: shared num = %d\n", num, shared_num);
6618                  uv_rwlock_rdunlock(&numlock);
6619                  printf("Reader %d: released lock\n", num);
6620              }
6621              uv_barrier_wait(&blocker);
6622          }
6623
6624          void writer(void *n)
6625          {
6626              int num = *(int *)n;
6627              int i;
6628              for (i = 0; i < 20; i++) {
6629                  uv_rwlock_wrlock(&numlock);
6630                  printf("Writer %d: acquired lock\n", num);
6631                  shared_num++;
6632                  printf("Writer %d: incremented shared num = %d\n", num, shared_num);
6633                  uv_rwlock_wrunlock(&numlock);
6634                  printf("Writer %d: released lock\n", num);
6635              }
6636              uv_barrier_wait(&blocker);
6637          }
6638
6639          int main()
6640          {
6641              uv_barrier_init(&blocker, 4);
6642
6643              shared_num = 0;
6644              uv_rwlock_init(&numlock);
6645
6646              uv_thread_t threads[3];
6647
6648              int thread_nums[] = {1, 2, 1};
6649              uv_thread_create(&threads[0], reader, &thread_nums[0]);
6650              uv_thread_create(&threads[1], reader, &thread_nums[1]);
6651
6652              uv_thread_create(&threads[2], writer, &thread_nums[2]);
6653
6654              uv_barrier_wait(&blocker);
6655              uv_barrier_destroy(&blocker);
6656
6657              uv_rwlock_destroy(&numlock);
6658              return 0;
6659          }
6660
6661
6662       Run this and observe how the readers will sometimes overlap. In case of
6663       multiple writers, schedulers will usually give them higher priority, so
6664       if you add two writers, you'll see that both  writers  tend  to  finish
6665       first before the readers get a chance again.
6666
6667       We  also  use barriers in the above example so that the main thread can
6668       wait for all readers and writers to indicate they have ended.
6669
6670   Others
6671       libuv also supports semaphores, condition variables and  barriers  with
6672       APIs very similar to their pthread counterparts.
6673
6674       In  addition, libuv provides a convenience function uv_once(). Multiple
6675       threads can attempt to call uv_once() with a given guard and a function
6676       pointer,  only the first one will win, the function will be called once
6677       and only once:
6678
6679          /* Initialize guard */
6680          static uv_once_t once_only = UV_ONCE_INIT;
6681
6682          int i = 0;
6683
6684          void increment() {
6685              i++;
6686          }
6687
6688          void thread1() {
6689              /* ... work */
6690              uv_once(once_only, increment);
6691          }
6692
6693          void thread2() {
6694              /* ... work */
6695              uv_once(once_only, increment);
6696          }
6697
6698          int main() {
6699              /* ... spawn threads */
6700          }
6701
6702       After all threads are done, i == 1.
6703
6704       libuv v0.11.11 onwards  also  added  a  uv_key_t  struct  and  api  for
6705       thread-local storage.
6706
6707   libuv work queue
6708       uv_queue_work() is a convenience function that allows an application to
6709       run a task in a separate thread, and have a callback that is  triggered
6710       when  the  task  is  done.  A  seemingly  simple  function,  what makes
6711       uv_queue_work() tempting is that it allows potentially any  third-party
6712       libraries  to  be used with the event-loop paradigm. When you use event
6713       loops, it is imperative to make sure that no function which runs  peri‐
6714       odically  in the loop thread blocks when performing I/O or is a serious
6715       CPU hog, because this means that the loop slows down and events are not
6716       being handled at full capacity.
6717
6718       However,  a  lot of existing code out there features blocking functions
6719       (for example a routine which performs I/O under the hood)  to  be  used
6720       with  threads  if  you want responsiveness (the classic 'one thread per
6721       client' server model), and getting them to play with an event loop  li‐
6722       brary generally involves rolling your own system of running the task in
6723       a separate thread.  libuv just provides a  convenient  abstraction  for
6724       this.
6725
6726       Here is a simple example inspired by node.js is cancer. We are going to
6727       calculate fibonacci numbers, sleeping a bit along the way, but  run  it
6728       in  a  separate thread so that the blocking and CPU bound task does not
6729       prevent the event loop from performing other activities.
6730
6731       queue-work/main.c - lazy fibonacci
6732
6733          void fib(uv_work_t *req) {
6734              int n = *(int *) req->data;
6735              if (random() % 2)
6736                  sleep(1);
6737              else
6738                  sleep(3);
6739              long fib = fib_(n);
6740              fprintf(stderr, "%dth fibonacci is %lu\n", n, fib);
6741          }
6742
6743          void after_fib(uv_work_t *req, int status) {
6744              fprintf(stderr, "Done calculating %dth fibonacci\n", *(int *) req->data);
6745          }
6746
6747
6748       The actual task function is simple, nothing to show that it is going to
6749       be  run  in a separate thread. The uv_work_t structure is the clue. You
6750       can pass arbitrary data through it using the void* data field  and  use
6751       it  to  communicate  to  and from the thread. But be sure you are using
6752       proper locks if you are changing things while both threads may be  run‐
6753       ning.
6754
6755       The trigger is uv_queue_work:
6756
6757       queue-work/main.c
6758
6759          int main() {
6760              loop = uv_default_loop();
6761
6762              int data[FIB_UNTIL];
6763              uv_work_t req[FIB_UNTIL];
6764              int i;
6765              for (i = 0; i < FIB_UNTIL; i++) {
6766                  data[i] = i;
6767                  req[i].data = (void *) &data[i];
6768                  uv_queue_work(loop, &req[i], fib, after_fib);
6769              }
6770
6771              return uv_run(loop, UV_RUN_DEFAULT);
6772          }
6773
6774
6775       The  thread  function will be launched in a separate thread, passed the
6776       uv_work_t structure and once the function returns, the  after  function
6777       will  be  called on the thread the event loop is running in. It will be
6778       passed the same structure.
6779
6780       For writing wrappers to blocking libraries, a common pattern is to  use
6781       a baton to exchange data.
6782
6783       Since  libuv  version  0.9.4  an  additional  function, uv_cancel(), is
6784       available. This allows you to cancel tasks on  the  libuv  work  queue.
6785       Only  tasks  that are yet to be started can be cancelled. If a task has
6786       already started executing, or it has  finished  executing,  uv_cancel()
6787       will fail.
6788
6789       uv_cancel()  is  useful  to  cleanup pending tasks if the user requests
6790       termination. For example, a music player may queue up multiple directo‐
6791       ries to be scanned for audio files. If the user terminates the program,
6792       it should quit quickly and not wait until all pending requests are run.
6793
6794       Let's modify the fibonacci example to demonstrate uv_cancel(). We first
6795       set up a signal handler for termination.
6796
6797       queue-cancel/main.c
6798
6799          int main() {
6800              loop = uv_default_loop();
6801
6802              int data[FIB_UNTIL];
6803              int i;
6804              for (i = 0; i < FIB_UNTIL; i++) {
6805                  data[i] = i;
6806                  fib_reqs[i].data = (void *) &data[i];
6807                  uv_queue_work(loop, &fib_reqs[i], fib, after_fib);
6808              }
6809
6810              uv_signal_t sig;
6811              uv_signal_init(loop, &sig);
6812              uv_signal_start(&sig, signal_handler, SIGINT);
6813
6814              return uv_run(loop, UV_RUN_DEFAULT);
6815          }
6816
6817
6818       When  the  user  triggers the signal by pressing Ctrl+C we send uv_can‐
6819       cel() to all the workers. uv_cancel() will return 0 for those that  are
6820       already executing or finished.
6821
6822       queue-cancel/main.c
6823
6824          void signal_handler(uv_signal_t *req, int signum)
6825          {
6826              printf("Signal received!\n");
6827              int i;
6828              for (i = 0; i < FIB_UNTIL; i++) {
6829                  uv_cancel((uv_req_t*) &fib_reqs[i]);
6830              }
6831              uv_signal_stop(req);
6832          }
6833
6834
6835       For  tasks  that  do  get cancelled successfully, the after function is
6836       called with status set to UV_ECANCELED.
6837
6838       queue-cancel/main.c
6839
6840          void after_fib(uv_work_t *req, int status) {
6841              if (status == UV_ECANCELED)
6842                  fprintf(stderr, "Calculation of %d cancelled.\n", *(int *) req->data);
6843          }
6844
6845
6846       uv_cancel() can also be used  with  uv_fs_t  and  uv_getaddrinfo_t  re‐
6847       quests. For the filesystem family of functions, uv_fs_t.errorno will be
6848       set to UV_ECANCELED.
6849
6850       TIP:
6851          A well designed program would have a way to terminate  long  running
6852          workers that have already started executing. Such a worker could pe‐
6853          riodically check for a variable that only the main process  sets  to
6854          signal termination.
6855
6856   Inter-thread communication
6857       Sometimes you want various threads to actually send each other messages
6858       while they are running. For example you might be running some long  du‐
6859       ration task in a separate thread (perhaps using uv_queue_work) but want
6860       to notify progress to the main thread. This is a simple example of hav‐
6861       ing  a  download  manager  informing  the user of the status of running
6862       downloads.
6863
6864       progress/main.c
6865
6866          uv_loop_t *loop;
6867          uv_async_t async;
6868
6869          int main() {
6870              loop = uv_default_loop();
6871
6872              uv_work_t req;
6873              int size = 10240;
6874              req.data = (void*) &size;
6875
6876              uv_async_init(loop, &async, print_progress);
6877              uv_queue_work(loop, &req, fake_download, after);
6878
6879              return uv_run(loop, UV_RUN_DEFAULT);
6880          }
6881
6882
6883       The async thread communication works on loops so  although  any  thread
6884       can  be  the  message  sender, only threads with libuv loops can be re‐
6885       ceivers (or rather the loop is the receiver).  libuv  will  invoke  the
6886       callback (print_progress) with the async watcher whenever it receives a
6887       message.
6888
6889       WARNING:
6890          It is important to realize that since the message send is async, the
6891          callback may be invoked immediately after uv_async_send is called in
6892          another thread, or it may be invoked after some time. libuv may also
6893          combine  multiple  calls  to  uv_async_send and invoke your callback
6894          only once. The only guarantee that libuv makes is  --  The  callback
6895          function is called at least once after the call to uv_async_send. If
6896          you have no pending calls to uv_async_send, the  callback  won't  be
6897          called. If you make two or more calls, and libuv hasn't had a chance
6898          to run the callback yet, it may invoke your callback only  once  for
6899          the  multiple invocations of uv_async_send. Your callback will never
6900          be called twice for just one event.
6901
6902       progress/main.c
6903
6904          double percentage;
6905
6906          void fake_download(uv_work_t *req) {
6907              int size = *((int*) req->data);
6908              int downloaded = 0;
6909              while (downloaded < size) {
6910                  percentage = downloaded*100.0/size;
6911                  async.data = (void*) &percentage;
6912                  uv_async_send(&async);
6913
6914                  sleep(1);
6915                  downloaded += (200+random())%1000; // can only download max 1000bytes/sec,
6916                                                     // but at least a 200;
6917              }
6918          }
6919
6920
6921       In the download function, we modify the progress  indicator  and  queue
6922       the message for delivery with uv_async_send. Remember: uv_async_send is
6923       also non-blocking and will return immediately.
6924
6925       progress/main.c
6926
6927          void print_progress(uv_async_t *handle) {
6928              double percentage = *((double*) handle->data);
6929              fprintf(stderr, "Downloaded %.2f%%\n", percentage);
6930          }
6931
6932
6933       The callback is a standard libuv pattern, extracting the data from  the
6934       watcher.
6935
6936       Finally it is important to remember to clean up the watcher.
6937
6938       progress/main.c
6939
6940          void after(uv_work_t *req, int status) {
6941              fprintf(stderr, "Download complete\n");
6942              uv_close((uv_handle_t*) &async, NULL);
6943          }
6944
6945
6946       After  this  example,  which  showed  the  abuse  of  the  data  field,
6947       bnoordhuis pointed out that using the data field is  not  thread  safe,
6948       and  uv_async_send()  is actually only meant to wake up the event loop.
6949       Use a mutex or rwlock to ensure accesses are performed in the right or‐
6950       der.
6951
6952       NOTE:
6953          mutexes  and  rwlocks  DO  NOT work inside a signal handler, whereas
6954          uv_async_send does.
6955
6956       One use case where uv_async_send is  required  is  when  interoperating
6957       with  libraries  that  require thread affinity for their functionality.
6958       For example in node.js, a v8 engine instance, contexts and its  objects
6959       are  bound to the thread that the v8 instance was started in. Interact‐
6960       ing with v8 data structures from another thread can lead  to  undefined
6961       results. Now consider some node.js module which binds a third party li‐
6962       brary. It may go something like this:
6963
6964       1. In node, the third party library is set up with a  JavaScript  call‐
6965          back to be invoked for more information:
6966
6967             var lib = require('lib');
6968             lib.on_progress(function() {
6969                 console.log("Progress");
6970             });
6971
6972             lib.do();
6973
6974             // do other stuff
6975
6976       2. lib.do  is  supposed  to  be non-blocking but the third party lib is
6977          blocking, so the binding uses uv_queue_work.
6978
6979       3. The actual work being done in a separate thread wants to invoke  the
6980          progress callback, but cannot directly call into v8 to interact with
6981          JavaScript. So it uses uv_async_send.
6982
6983       4. The async callback, invoked in the main loop thread, which is the v8
6984          thread, then interacts with v8 to invoke the JavaScript callback.
6985
6986
6987                                        ----
6988
6989
6990
6991   Processes
6992       libuv  offers  considerable  child  process management, abstracting the
6993       platform differences and allowing communication with the child  process
6994       using streams or named pipes.
6995
6996       A  common  idiom in Unix is for every process to do one thing and do it
6997       well. In such a case, a process often uses multiple child processes  to
6998       achieve tasks (similar to using pipes in shells). A multi-process model
6999       with messages may also be easier to reason about compared to  one  with
7000       threads and shared memory.
7001
7002       A  common refrain against event-based programs is that they cannot take
7003       advantage of multiple cores in modern computers.  In  a  multi-threaded
7004       program  the kernel can perform scheduling and assign different threads
7005       to different cores, improving performance. But an event loop  has  only
7006       one  thread.   The  workaround  can be to launch multiple processes in‐
7007       stead, with each process running an event loop, and each  process  get‐
7008       ting assigned to a separate CPU core.
7009
7010   Spawning child processes
7011       The  simplest case is when you simply want to launch a process and know
7012       when it exits. This is achieved using uv_spawn.
7013
7014       spawn/main.c
7015
7016          uv_loop_t *loop;
7017          uv_process_t child_req;
7018          uv_process_options_t options;
7019          int main() {
7020              loop = uv_default_loop();
7021
7022              char* args[3];
7023              args[0] = "mkdir";
7024              args[1] = "test-dir";
7025              args[2] = NULL;
7026
7027              options.exit_cb = on_exit;
7028              options.file = "mkdir";
7029              options.args = args;
7030
7031              int r;
7032              if ((r = uv_spawn(loop, &child_req, &options))) {
7033                  fprintf(stderr, "%s\n", uv_strerror(r));
7034                  return 1;
7035              } else {
7036                  fprintf(stderr, "Launched process with ID %d\n", child_req.pid);
7037              }
7038
7039              return uv_run(loop, UV_RUN_DEFAULT);
7040          }
7041
7042
7043       NOTE:
7044          options is implicitly initialized with zeros since it  is  a  global
7045          variable.   If  you  change options to a local variable, remember to
7046          initialize it to null out all unused fields:
7047
7048              uv_process_options_t options = {0};
7049
7050       The uv_process_t struct only acts as the handle, all  options  are  set
7051       via  uv_process_options_t.  To simply launch a process, you need to set
7052       only the file and args fields. file is the program  to  execute.  Since
7053       uv_spawn uses execvp(3) internally, there is no need to supply the full
7054       path. Finally as per underlying conventions, the arguments array has to
7055       be one larger than the number of arguments, with the last element being
7056       NULL.
7057
7058       After the call to uv_spawn, uv_process_t.pid will contain  the  process
7059       ID of the child process.
7060
7061       The  exit callback will be invoked with the exit status and the type of
7062       signal which caused the exit.
7063
7064       Note that it is important not to call uv_close before  the  exit  call‐
7065       back.
7066
7067       spawn/main.c
7068
7069
7070          void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) {
7071              fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
7072              uv_close((uv_handle_t*) req, NULL);
7073
7074
7075       It is required to close the process watcher after the process exits.
7076
7077   Changing process parameters
7078       Before  the child process is launched you can control the execution en‐
7079       vironment using fields in uv_process_options_t.
7080
7081   Change execution directory
7082       Set uv_process_options_t.cwd to the corresponding directory.
7083
7084   Set environment variables
7085       uv_process_options_t.env is a null-terminated array of strings, each of
7086       the  form  VAR=VALUE  used  to set up the environment variables for the
7087       process. Set this to NULL to inherit the environment  from  the  parent
7088       (this) process.
7089
7090   Option flags
7091       Setting  uv_process_options_t.flags  to  a  bitwise OR of the following
7092       flags, modifies the child process behaviour:
7093
7094UV_PROCESS_SETUID  -  sets  the  child's   execution   user   ID   to
7095         uv_process_options_t.uid.
7096
7097UV_PROCESS_SETGID   -   sets   the  child's  execution  group  ID  to
7098         uv_process_options_t.gid.
7099
7100       Changing the UID/GID is only supported on Unix, uv_spawn will  fail  on
7101       Windows with UV_ENOTSUP.
7102
7103UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS  -  No  quoting  or escaping of
7104         uv_process_options_t.args is done on Windows. Ignored on Unix.
7105
7106UV_PROCESS_DETACHED - Starts the child  process  in  a  new  session,
7107         which  will  keep running after the parent process exits. See example
7108         below.
7109
7110   Detaching processes
7111       Passing the flag UV_PROCESS_DETACHED can be used to launch daemons,  or
7112       child  processes which are independent of the parent so that the parent
7113       exiting does not affect it.
7114
7115       detach/main.c
7116
7117          int main() {
7118              loop = uv_default_loop();
7119
7120              char* args[3];
7121              args[0] = "sleep";
7122              args[1] = "100";
7123              args[2] = NULL;
7124
7125              options.exit_cb = NULL;
7126              options.file = "sleep";
7127              options.args = args;
7128              options.flags = UV_PROCESS_DETACHED;
7129
7130              int r;
7131              if ((r = uv_spawn(loop, &child_req, &options))) {
7132                  fprintf(stderr, "%s\n", uv_strerror(r));
7133                  return 1;
7134              }
7135              fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid);
7136              uv_unref((uv_handle_t*) &child_req);
7137
7138              return uv_run(loop, UV_RUN_DEFAULT);
7139
7140
7141       Just remember that the handle is still monitoring the  child,  so  your
7142       program won't exit. Use uv_unref() if you want to be more fire-and-for‐
7143       get.
7144
7145   Sending signals to processes
7146       libuv wraps the standard kill(2) system call on Unix and implements one
7147       with  similar  semantics  on  Windows, with one caveat: all of SIGTERM,
7148       SIGINT and SIGKILL, lead to termination of the process.  The  signature
7149       of uv_kill is:
7150
7151          uv_err_t uv_kill(int pid, int signum);
7152
7153       For processes started using libuv, you may use uv_process_kill instead,
7154       which accepts the uv_process_t watcher as the  first  argument,  rather
7155       than  the  pid.  In this case, remember to call uv_close on the watcher
7156       _after_ the exit callback has been called.
7157
7158   Signals
7159       libuv provides wrappers around Unix signals with some  Windows  support
7160       as well.
7161
7162       Use  uv_signal_init()  to  initialize  a handle and associate it with a
7163       loop. To listen for particular signals on  that  handler,  use  uv_sig‐
7164       nal_start() with the handler function. Each handler can only be associ‐
7165       ated with one signal number, with subsequent calls to uv_signal_start()
7166       overwriting  earlier  associations. Use uv_signal_stop() to stop watch‐
7167       ing. Here is a small example demonstrating the various possibilities:
7168
7169       signal/main.c
7170
7171          #include <stdio.h>
7172          #include <stdlib.h>
7173          #include <unistd.h>
7174          #include <uv.h>
7175
7176          uv_loop_t* create_loop()
7177          {
7178              uv_loop_t *loop = malloc(sizeof(uv_loop_t));
7179              if (loop) {
7180                uv_loop_init(loop);
7181              }
7182              return loop;
7183          }
7184
7185          void signal_handler(uv_signal_t *handle, int signum)
7186          {
7187              printf("Signal received: %d\n", signum);
7188              uv_signal_stop(handle);
7189          }
7190
7191          // two signal handlers in one loop
7192          void thread1_worker(void *userp)
7193          {
7194              uv_loop_t *loop1 = create_loop();
7195
7196              uv_signal_t sig1a, sig1b;
7197              uv_signal_init(loop1, &sig1a);
7198              uv_signal_start(&sig1a, signal_handler, SIGUSR1);
7199
7200              uv_signal_init(loop1, &sig1b);
7201              uv_signal_start(&sig1b, signal_handler, SIGUSR1);
7202
7203              uv_run(loop1, UV_RUN_DEFAULT);
7204          }
7205
7206          // two signal handlers, each in its own loop
7207          void thread2_worker(void *userp)
7208          {
7209              uv_loop_t *loop2 = create_loop();
7210              uv_loop_t *loop3 = create_loop();
7211
7212              uv_signal_t sig2;
7213              uv_signal_init(loop2, &sig2);
7214              uv_signal_start(&sig2, signal_handler, SIGUSR1);
7215
7216              uv_signal_t sig3;
7217              uv_signal_init(loop3, &sig3);
7218              uv_signal_start(&sig3, signal_handler, SIGUSR1);
7219
7220              while (uv_run(loop2, UV_RUN_NOWAIT) || uv_run(loop3, UV_RUN_NOWAIT)) {
7221              }
7222          }
7223
7224          int main()
7225          {
7226              printf("PID %d\n", getpid());
7227
7228              uv_thread_t thread1, thread2;
7229
7230              uv_thread_create(&thread1, thread1_worker, 0);
7231              uv_thread_create(&thread2, thread2_worker, 0);
7232
7233              uv_thread_join(&thread1);
7234              uv_thread_join(&thread2);
7235              return 0;
7236          }
7237
7238
7239       NOTE:
7240          uv_run(loop, UV_RUN_NOWAIT) is similar to uv_run(loop,  UV_RUN_ONCE)
7241          in  that it will process only one event. UV_RUN_ONCE blocks if there
7242          are no pending events, while UV_RUN_NOWAIT will return  immediately.
7243          We  use  NOWAIT  so  that one of the loops isn't starved because the
7244          other one has no pending activity.
7245
7246       Send SIGUSR1 to the process, and you'll find the handler being  invoked
7247       4  times, one for each uv_signal_t. The handler just stops each handle,
7248       so that the program exits. This sort of dispatch  to  all  handlers  is
7249       very  useful. A server using multiple event loops could ensure that all
7250       data was safely saved before termination, simply by every loop adding a
7251       watcher for SIGINT.
7252
7253   Child Process I/O
7254       A  normal,  newly  spawned process has its own set of file descriptors,
7255       with 0, 1 and 2 being stdin, stdout and stderr respectively.  Sometimes
7256       you  may  want  to  share file descriptors with the child. For example,
7257       perhaps your applications launches a sub-command and you want  any  er‐
7258       rors  to  go in the log file, but ignore stdout. For this you'd like to
7259       have stderr of the child be the same as the stderr of  the  parent.  In
7260       this  case, libuv supports inheriting file descriptors. In this sample,
7261       we invoke the test program, which is:
7262
7263       proc-streams/test.c
7264
7265          #include <stdio.h>
7266
7267          int main()
7268          {
7269              fprintf(stderr, "This is stderr\n");
7270              printf("This is stdout\n");
7271              return 0;
7272          }
7273
7274
7275       The actual program proc-streams runs this while  sharing  only  stderr.
7276       The file descriptors of the child process are set using the stdio field
7277       in uv_process_options_t. First set the stdio_count field to the  number
7278       of  file  descriptors being set. uv_process_options_t.stdio is an array
7279       of uv_stdio_container_t, which is:
7280
7281          typedef struct uv_stdio_container_s {
7282              uv_stdio_flags flags;
7283
7284              union {
7285                  uv_stream_t* stream;
7286                  int fd;
7287              } data;
7288          } uv_stdio_container_t;
7289
7290       where flags can have several values. Use UV_IGNORE if it isn't going to
7291       be  used.  If  the  first  three  stdio  fields are marked as UV_IGNORE
7292       they'll redirect to /dev/null.
7293
7294       Since we want to pass on  an  existing  descriptor,  we'll  use  UV_IN‐
7295       HERIT_FD.  Then we set the fd to stderr.
7296
7297       proc-streams/main.c
7298
7299
7300          int main() {
7301              loop = uv_default_loop();
7302
7303              /* ... */
7304
7305              options.stdio_count = 3;
7306              uv_stdio_container_t child_stdio[3];
7307              child_stdio[0].flags = UV_IGNORE;
7308              child_stdio[1].flags = UV_IGNORE;
7309              child_stdio[2].flags = UV_INHERIT_FD;
7310              child_stdio[2].data.fd = 2;
7311              options.stdio = child_stdio;
7312
7313              options.exit_cb = on_exit;
7314              options.file = args[0];
7315              options.args = args;
7316
7317              int r;
7318              if ((r = uv_spawn(loop, &child_req, &options))) {
7319                  fprintf(stderr, "%s\n", uv_strerror(r));
7320                  return 1;
7321              }
7322
7323              return uv_run(loop, UV_RUN_DEFAULT);
7324          }
7325
7326
7327       If  you  run proc-stream you'll see that only the line "This is stderr"
7328       will be displayed. Try marking stdout as being inherited  and  see  the
7329       output.
7330
7331       It  is  dead  simple  to apply this redirection to streams.  By setting
7332       flags to UV_INHERIT_STREAM and setting data.stream to the stream in the
7333       parent  process,  the  child  process can treat that stream as standard
7334       I/O. This can be used to implement something like CGI.
7335
7336       A sample CGI script/executable is:
7337
7338       cgi/tick.c
7339
7340          #include <stdio.h>
7341          #include <unistd.h>
7342
7343          int main() {
7344              int i;
7345              for (i = 0; i < 10; i++) {
7346                  printf("tick\n");
7347                  fflush(stdout);
7348                  sleep(1);
7349              }
7350              printf("BOOM!\n");
7351              return 0;
7352          }
7353
7354
7355       The CGI server combines the concepts from this chapter  and  Networking
7356       so  that  every client is sent ten ticks after which that connection is
7357       closed.
7358
7359       cgi/main.c
7360
7361
7362          void on_new_connection(uv_stream_t *server, int status) {
7363              if (status == -1) {
7364                  // error!
7365                  return;
7366              }
7367
7368              uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
7369              uv_tcp_init(loop, client);
7370              if (uv_accept(server, (uv_stream_t*) client) == 0) {
7371                  invoke_cgi_script(client);
7372              }
7373              else {
7374                  uv_close((uv_handle_t*) client, NULL);
7375              }
7376
7377
7378       Here we simply accept  the  TCP  connection  and  pass  on  the  socket
7379       (stream) to invoke_cgi_script.
7380
7381       cgi/main.c
7382
7383
7384              args[1] = NULL;
7385
7386              /* ... finding the executable path and setting up arguments ... */
7387
7388              options.stdio_count = 3;
7389              uv_stdio_container_t child_stdio[3];
7390              child_stdio[0].flags = UV_IGNORE;
7391              child_stdio[1].flags = UV_INHERIT_STREAM;
7392              child_stdio[1].data.stream = (uv_stream_t*) client;
7393              child_stdio[2].flags = UV_IGNORE;
7394              options.stdio = child_stdio;
7395
7396              options.exit_cb = cleanup_handles;
7397              options.file = args[0];
7398              options.args = args;
7399
7400              // Set this so we can close the socket after the child process exits.
7401              child_req.data = (void*) client;
7402              int r;
7403              if ((r = uv_spawn(loop, &child_req, &options))) {
7404                  fprintf(stderr, "%s\n", uv_strerror(r));
7405
7406
7407       The  stdout of the CGI script is set to the socket so that whatever our
7408       tick script prints, gets sent to the client. By using processes, we can
7409       offload  the  read/write buffering to the operating system, so in terms
7410       of convenience this is great. Just be warned that creating processes is
7411       a costly task.
7412
7413   Parent-child IPC
7414       A  parent  and  child can have one or two way communication over a pipe
7415       created by settings uv_stdio_container_t.flags to a  bit-wise  combina‐
7416       tion  of  UV_CREATE_PIPE  and UV_READABLE_PIPE or UV_WRITABLE_PIPE. The
7417       read/write flag is from the perspective of the child process.  In  this
7418       case, the uv_stream_t* stream field must be set to point to an initial‐
7419       ized, unopened uv_pipe_t instance.
7420
7421   New stdio Pipes
7422       The uv_pipe_t structure represents more than just pipe(7) (or  |),  but
7423       supports  any  streaming file-like objects. On Windows, the only object
7424       of that description is the Named Pipe.  On Unix, this could be  any  of
7425       Unix  Domain Socket, or derived from mkfifo(1), or it could actually be
7426       a pipe(7).  When uv_spawn initializes a uv_pipe_t due  to  the  UV_CRE‐
7427       ATE_PIPE flag, it opts for creating a socketpair(2).
7428
7429       This  is  intended for the purpose of allowing multiple libuv processes
7430       to communicate with IPC. This is discussed below.
7431
7432   Arbitrary process IPC
7433       Since domain sockets [1] can have a well known name and a  location  in
7434       the  file-system  they can be used for IPC between unrelated processes.
7435       The D-BUS system used by open source desktop environments  uses  domain
7436       sockets  for  event  notification.  Various applications can then react
7437       when a contact comes online or new  hardware  is  detected.  The  MySQL
7438       server also runs a domain socket on which clients can interact with it.
7439
7440       When  using domain sockets, a client-server pattern is usually followed
7441       with the creator/owner of the socket acting as the  server.  After  the
7442       initial  setup, messaging is no different from TCP, so we'll re-use the
7443       echo server example.
7444
7445       pipe-echo-server/main.c
7446
7447          void remove_sock(int sig) {
7448              uv_fs_t req;
7449              uv_fs_unlink(loop, &req, PIPENAME, NULL);
7450              exit(0);
7451          }
7452
7453          int main() {
7454              loop = uv_default_loop();
7455
7456              uv_pipe_t server;
7457              uv_pipe_init(loop, &server, 0);
7458
7459              signal(SIGINT, remove_sock);
7460
7461              int r;
7462              if ((r = uv_pipe_bind(&server, PIPENAME))) {
7463                  fprintf(stderr, "Bind error %s\n", uv_err_name(r));
7464                  return 1;
7465              }
7466              if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) {
7467                  fprintf(stderr, "Listen error %s\n", uv_err_name(r));
7468                  return 2;
7469              }
7470              return uv_run(loop, UV_RUN_DEFAULT);
7471          }
7472
7473
7474       We name the socket echo.sock which means it will be created in the  lo‐
7475       cal directory. This socket now behaves no different from TCP sockets as
7476       far as the stream API is concerned. You  can  test  this  server  using
7477       socat:
7478
7479          $ socat - /path/to/socket
7480
7481       A client which wants to connect to a domain socket will use:
7482
7483          void uv_pipe_connect(uv_connect_t *req, uv_pipe_t *handle, const char *name, uv_connect_cb cb);
7484
7485       where  name  will  be  echo.sock or similar. On Unix systems, name must
7486       point to a valid file (e.g. /tmp/echo.sock). On Windows, name follows a
7487       \\?\pipe\echo.sock format.
7488
7489   Sending file descriptors over pipes
7490       The cool thing about domain sockets is that file descriptors can be ex‐
7491       changed between processes by sending them over a  domain  socket.  This
7492       allows processes to hand off their I/O to other processes. Applications
7493       include load-balancing servers, worker processes and other ways to make
7494       optimum  use  of  CPU. libuv only supports sending TCP sockets or other
7495       pipes over pipes for now.
7496
7497       To demonstrate, we will look at a echo server implementation that hands
7498       of  clients  to worker processes in a round-robin fashion. This program
7499       is a bit involved, and while only snippets are included in the book, it
7500       is recommended to read the full code to really understand it.
7501
7502       The worker process is quite simple, since the file-descriptor is handed
7503       over to it by the master.
7504
7505       multi-echo-server/worker.c
7506
7507
7508          uv_loop_t *loop;
7509          uv_pipe_t queue;
7510          int main() {
7511              loop = uv_default_loop();
7512
7513              uv_pipe_init(loop, &queue, 1 /* ipc */);
7514              uv_pipe_open(&queue, 0);
7515              uv_read_start((uv_stream_t*)&queue, alloc_buffer, on_new_connection);
7516              return uv_run(loop, UV_RUN_DEFAULT);
7517          }
7518
7519
7520       queue is the pipe connected to the master process  on  the  other  end,
7521       along  which  new file descriptors get sent. It is important to set the
7522       ipc argument of uv_pipe_init to 1 to indicate this pipe  will  be  used
7523       for  inter-process  communication! Since the master will write the file
7524       handle to the standard input of the worker,  we  connect  the  pipe  to
7525       stdin using uv_pipe_open.
7526
7527       multi-echo-server/worker.c
7528
7529          void on_new_connection(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) {
7530              if (nread < 0) {
7531                  if (nread != UV_EOF)
7532                      fprintf(stderr, "Read error %s\n", uv_err_name(nread));
7533                  uv_close((uv_handle_t*) q, NULL);
7534                  return;
7535              }
7536
7537              uv_pipe_t *pipe = (uv_pipe_t*) q;
7538              if (!uv_pipe_pending_count(pipe)) {
7539                  fprintf(stderr, "No pending count\n");
7540                  return;
7541              }
7542
7543              uv_handle_type pending = uv_pipe_pending_type(pipe);
7544              assert(pending == UV_TCP);
7545
7546              uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
7547              uv_tcp_init(loop, client);
7548              if (uv_accept(q, (uv_stream_t*) client) == 0) {
7549                  uv_os_fd_t fd;
7550                  uv_fileno((const uv_handle_t*) client, &fd);
7551                  fprintf(stderr, "Worker %d: Accepted fd %d\n", getpid(), fd);
7552                  uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
7553              }
7554              else {
7555                  uv_close((uv_handle_t*) client, NULL);
7556              }
7557          }
7558
7559
7560       First we call uv_pipe_pending_count() to ensure that a handle is avail‐
7561       able to read out. If your program could deal with  different  types  of
7562       handles, uv_pipe_pending_type() can be used to determine the type.  Al‐
7563       though accept seems odd in this code, it actually makes sense. What ac‐
7564       cept  traditionally does is get a file descriptor (the client) from an‐
7565       other file descriptor (The listening socket). Which is exactly what  we
7566       do here. Fetch the file descriptor (client) from queue. From this point
7567       the worker does standard echo server stuff.
7568
7569       Turning now to the master, let's take a look at  how  the  workers  are
7570       launched to allow load balancing.
7571
7572       multi-echo-server/main.c
7573
7574          struct child_worker {
7575              uv_process_t req;
7576              uv_process_options_t options;
7577              uv_pipe_t pipe;
7578          } *workers;
7579
7580
7581       The  child_worker structure wraps the process, and the pipe between the
7582       master and the individual process.
7583
7584       multi-echo-server/main.c
7585
7586          void setup_workers() {
7587              round_robin_counter = 0;
7588
7589              // ...
7590
7591              // launch same number of workers as number of CPUs
7592              uv_cpu_info_t *info;
7593              int cpu_count;
7594              uv_cpu_info(&info, &cpu_count);
7595              uv_free_cpu_info(info, cpu_count);
7596
7597              child_worker_count = cpu_count;
7598
7599              workers = calloc(cpu_count, sizeof(struct child_worker));
7600              while (cpu_count--) {
7601                  struct child_worker *worker = &workers[cpu_count];
7602                  uv_pipe_init(loop, &worker->pipe, 1);
7603
7604                  uv_stdio_container_t child_stdio[3];
7605                  child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE;
7606                  child_stdio[0].data.stream = (uv_stream_t*) &worker->pipe;
7607                  child_stdio[1].flags = UV_IGNORE;
7608                  child_stdio[2].flags = UV_INHERIT_FD;
7609                  child_stdio[2].data.fd = 2;
7610
7611                  worker->options.stdio = child_stdio;
7612                  worker->options.stdio_count = 3;
7613
7614                  worker->options.exit_cb = close_process_handle;
7615                  worker->options.file = args[0];
7616                  worker->options.args = args;
7617
7618                  uv_spawn(loop, &worker->req, &worker->options);
7619                  fprintf(stderr, "Started worker %d\n", worker->req.pid);
7620              }
7621          }
7622
7623
7624       In setting up the workers, we use the nifty libuv function  uv_cpu_info
7625       to  get the number of CPUs so we can launch an equal number of workers.
7626       Again it is important to initialize the pipe acting as the IPC  channel
7627       with  the third argument as 1. We then indicate that the child process'
7628       stdin is to be a readable pipe (from the point of view of  the  child).
7629       Everything  is  straightforward till here. The workers are launched and
7630       waiting for file descriptors to be written to their standard input.
7631
7632       It is in on_new_connection (the TCP infrastructure  is  initialized  in
7633       main()), that we accept the client socket and pass it along to the next
7634       worker in the round-robin.
7635
7636       multi-echo-server/main.c
7637
7638          void on_new_connection(uv_stream_t *server, int status) {
7639              if (status == -1) {
7640                  // error!
7641                  return;
7642              }
7643
7644              uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
7645              uv_tcp_init(loop, client);
7646              if (uv_accept(server, (uv_stream_t*) client) == 0) {
7647                  uv_write_t *write_req = (uv_write_t*) malloc(sizeof(uv_write_t));
7648                  dummy_buf = uv_buf_init("a", 1);
7649                  struct child_worker *worker = &workers[round_robin_counter];
7650                  uv_write2(write_req, (uv_stream_t*) &worker->pipe, &dummy_buf, 1, (uv_stream_t*) client, NULL);
7651                  round_robin_counter = (round_robin_counter + 1) % child_worker_count;
7652              }
7653              else {
7654                  uv_close((uv_handle_t*) client, NULL);
7655              }
7656          }
7657
7658
7659       The uv_write2 call handles all the abstraction and it is simply a  mat‐
7660       ter  of passing in the handle (client) as the right argument. With this
7661       our multi-process echo server is operational.
7662
7663       Thanks to Kyle for pointing out that uv_write2() requires  a  non-empty
7664       buffer even when sending handles.
7665
7666
7667                                        ----
7668
7669
7670
7671       [1]  In  this  section domain sockets stands in for named pipes on Win‐
7672            dows as well.
7673
7674   Advanced event loops
7675       libuv provides considerable user control over event loops, and you  can
7676       achieve  interesting  results  by juggling multiple loops. You can also
7677       embed libuv's event loop into another event loop based library -- imag‐
7678       ine  a  Qt  based UI, and Qt's event loop driving a libuv backend which
7679       does intensive system level tasks.
7680
7681   Stopping an event loop
7682       uv_stop() can be used to stop an event loop. The earliest the loop will
7683       stop  running is on the next iteration, possibly later. This means that
7684       events that are ready to be processed in this  iteration  of  the  loop
7685       will  still  be processed, so uv_stop() can't be used as a kill switch.
7686       When uv_stop() is called, the loop won't block for i/o on  this  itera‐
7687       tion.  The  semantics  of these things can be a bit difficult to under‐
7688       stand, so let's look at uv_run() where all the control flow occurs.
7689
7690       src/unix/core.c - uv_run
7691
7692
7693            switch (handle->type) {
7694              case UV_PREPARE:
7695              case UV_CHECK:
7696              case UV_IDLE:
7697              case UV_ASYNC:
7698              case UV_TIMER:
7699              case UV_PROCESS:
7700              case UV_FS_EVENT:
7701              case UV_FS_POLL:
7702              case UV_POLL:
7703                break;
7704
7705              case UV_SIGNAL:
7706                /* If there are any caught signals "trapped" in the signal pipe,
7707                 * we can't call the close callback yet. Reinserting the handle
7708                 * into the closing queue makes the event loop spin but that's
7709                 * okay because we only need to deliver the pending events.
7710                 */
7711                sh = (uv_signal_t*) handle;
7712                if (sh->caught_signals > sh->dispatched_signals) {
7713
7714
7715       stop_flag is set by uv_stop(). Now  all  libuv  callbacks  are  invoked
7716       within  the  event  loop,  which is why invoking uv_stop() in them will
7717       still lead to this iteration of the loop occurring. First libuv updates
7718       timers,  then  runs  pending timer, idle and prepare callbacks, and in‐
7719       vokes any pending I/O callbacks. If you were to call uv_stop()  in  any
7720       of  them,  stop_flag  would be set. This causes uv_backend_timeout() to
7721       return 0, which is why the loop does not block on I/O. If on the  other
7722       hand,  you  called  uv_stop() in one of the check handlers, I/O has al‐
7723       ready finished and is not affected.
7724
7725       uv_stop() is useful to shutdown a loop when a result has been  computed
7726       or  there  is  an error, without having to ensure that all handlers are
7727       stopped one by one.
7728
7729       Here is a simple example that stops the loop and demonstrates  how  the
7730       current iteration of the loop still takes places.
7731
7732       uvstop/main.c
7733
7734          #include <stdio.h>
7735          #include <uv.h>
7736
7737          int64_t counter = 0;
7738
7739          void idle_cb(uv_idle_t *handle) {
7740              printf("Idle callback\n");
7741              counter++;
7742
7743              if (counter >= 5) {
7744                  uv_stop(uv_default_loop());
7745                  printf("uv_stop() called\n");
7746              }
7747          }
7748
7749          void prep_cb(uv_prepare_t *handle) {
7750              printf("Prep callback\n");
7751          }
7752
7753          int main() {
7754              uv_idle_t idler;
7755              uv_prepare_t prep;
7756
7757              uv_idle_init(uv_default_loop(), &idler);
7758              uv_idle_start(&idler, idle_cb);
7759
7760              uv_prepare_init(uv_default_loop(), &prep);
7761              uv_prepare_start(&prep, prep_cb);
7762
7763              uv_run(uv_default_loop(), UV_RUN_DEFAULT);
7764
7765              return 0;
7766          }
7767
7768
7769   Utilities
7770       This  chapter catalogues tools and techniques which are useful for com‐
7771       mon tasks.  The libev man page already covers some patterns  which  can
7772       be adopted to libuv through simple API changes. It also covers parts of
7773       the libuv API that don't require entire chapters dedicated to them.
7774
7775   Timers
7776       Timers invoke the callback after a certain time has elapsed  since  the
7777       timer  was  started.  libuv timers can also be set to invoke at regular
7778       intervals instead of just once.
7779
7780       Simple use is to init a watcher and start it with a  timeout,  and  op‐
7781       tional repeat.  Timers can be stopped at any time.
7782
7783          uv_timer_t timer_req;
7784
7785          uv_timer_init(loop, &timer_req);
7786          uv_timer_start(&timer_req, callback, 5000, 2000);
7787
7788       will  start  a repeating timer, which first starts 5 seconds (the time‐
7789       out) after the execution of uv_timer_start, then repeats every  2  sec‐
7790       onds (the repeat). Use:
7791
7792          uv_timer_stop(&timer_req);
7793
7794       to  stop the timer. This can be used safely from within the callback as
7795       well.
7796
7797       The repeat interval can be modified at any time with:
7798
7799          uv_timer_set_repeat(uv_timer_t *timer, int64_t repeat);
7800
7801       which will take effect when possible. If this function is called from a
7802       timer callback, it means:
7803
7804       • If  the  timer was non-repeating, the timer has already been stopped.
7805         Use uv_timer_start again.
7806
7807       • If the timer is repeating, the next timeout has already  been  sched‐
7808         uled,  so  the  old repeat interval will be used once more before the
7809         timer switches to the new interval.
7810
7811       The utility function:
7812
7813          int uv_timer_again(uv_timer_t *)
7814
7815       applies only to repeating timers and  is  equivalent  to  stopping  the
7816       timer  and then starting it with both initial timeout and repeat set to
7817       the old repeat value. If the timer hasn't been started it fails  (error
7818       code UV_EINVAL) and returns -1.
7819
7820       An actual timer example is in the reference count section.
7821
7822   Event loop reference count
7823       The event loop only runs as long as there are active handles. This sys‐
7824       tem works by having every handle increase the reference  count  of  the
7825       event  loop  when it is started and decreasing the reference count when
7826       stopped. It is also possible to manually change the reference count  of
7827       handles using:
7828
7829          void uv_ref(uv_handle_t*);
7830          void uv_unref(uv_handle_t*);
7831
7832       These functions can be used to allow a loop to exit even when a watcher
7833       is active or to use custom objects to keep the loop alive.
7834
7835       The latter can be used with interval timers. You might have  a  garbage
7836       collector  which  runs  every  X seconds, or your network service might
7837       send a heartbeat to others periodically, but you don't want to have  to
7838       stop  them  along  all clean exit paths or error scenarios. Or you want
7839       the program to exit when all your other watchers are done. In that case
7840       just  unref  the  timer immediately after creation so that if it is the
7841       only watcher running then uv_run will still exit.
7842
7843       This is also used in node.js where some libuv methods are being bubbled
7844       up  to  the  JS  API. A uv_handle_t (the superclass of all watchers) is
7845       created per JS object and can be ref/unrefed.
7846
7847       ref-timer/main.c
7848
7849          uv_loop_t *loop;
7850          uv_timer_t gc_req;
7851          uv_timer_t fake_job_req;
7852
7853          int main() {
7854              loop = uv_default_loop();
7855
7856              uv_timer_init(loop, &gc_req);
7857              uv_unref((uv_handle_t*) &gc_req);
7858
7859              uv_timer_start(&gc_req, gc, 0, 2000);
7860
7861              // could actually be a TCP download or something
7862              uv_timer_init(loop, &fake_job_req);
7863              uv_timer_start(&fake_job_req, fake_job, 9000, 0);
7864              return uv_run(loop, UV_RUN_DEFAULT);
7865          }
7866
7867
7868       We initialize the garbage collector timer, then immediately  unref  it.
7869       Observe how after 9 seconds, when the fake job is done, the program au‐
7870       tomatically exits, even though the garbage collector is still running.
7871
7872   Idler pattern
7873       The callbacks of idle handles are invoked once per event loop. The idle
7874       callback  can  be  used to perform some very low priority activity. For
7875       example, you could dispatch a summary of the daily application  perfor‐
7876       mance to the developers for analysis during periods of idleness, or use
7877       the application's CPU time to perform  SETI  calculations  :)  An  idle
7878       watcher is also useful in a GUI application. Say you are using an event
7879       loop for a file download. If the TCP socket is still being  established
7880       and  no  other  events  are present your event loop will pause (block),
7881       which means your progress bar will freeze and the user will face an un‐
7882       responsive  application.  In  such  a case queue up and idle watcher to
7883       keep the UI operational.
7884
7885       idle-compute/main.c
7886
7887          uv_loop_t *loop;
7888          uv_fs_t stdin_watcher;
7889          uv_idle_t idler;
7890          char buffer[1024];
7891
7892          int main() {
7893              loop = uv_default_loop();
7894
7895              uv_idle_init(loop, &idler);
7896
7897              uv_buf_t buf = uv_buf_init(buffer, 1024);
7898              uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type);
7899              uv_idle_start(&idler, crunch_away);
7900              return uv_run(loop, UV_RUN_DEFAULT);
7901          }
7902
7903
7904       Here we initialize the idle watcher and queue it up along with the  ac‐
7905       tual  events  we  are interested in. crunch_away will now be called re‐
7906       peatedly until the user types something and  presses  Return.  Then  it
7907       will be interrupted for a brief amount as the loop deals with the input
7908       data, after which it will keep calling the idle callback again.
7909
7910       idle-compute/main.c
7911
7912          void crunch_away(uv_idle_t* handle) {
7913              // Compute extra-terrestrial life
7914              // fold proteins
7915              // computer another digit of PI
7916              // or similar
7917              fprintf(stderr, "Computing PI...\n");
7918              // just to avoid overwhelming your terminal emulator
7919              uv_idle_stop(handle);
7920          }
7921
7922
7923
7924   Passing data to worker thread
7925       When using uv_queue_work you'll  usually  need  to  pass  complex  data
7926       through  to  the worker thread. The solution is to use a struct and set
7927       uv_work_t.data to point to it.  A  slight  variation  is  to  have  the
7928       uv_work_t  itself  as  the  first member of this struct (called a baton
7929       [1]).  This allows cleaning up the work request and all the data in one
7930       free call.
7931
7932          struct ftp_baton {
7933              uv_work_t req;
7934              char *host;
7935              int port;
7936              char *username;
7937              char *password;
7938          }
7939
7940          ftp_baton *baton = (ftp_baton*) malloc(sizeof(ftp_baton));
7941          baton->req.data = (void*) baton;
7942          baton->host = strdup("my.webhost.com");
7943          baton->port = 21;
7944          // ...
7945
7946          uv_queue_work(loop, &baton->req, ftp_session, ftp_cleanup);
7947
7948       Here we create the baton and queue the task.
7949
7950       Now the task function can extract the data it needs:
7951
7952          void ftp_session(uv_work_t *req) {
7953              ftp_baton *baton = (ftp_baton*) req->data;
7954
7955              fprintf(stderr, "Connecting to %s\n", baton->host);
7956          }
7957
7958          void ftp_cleanup(uv_work_t *req) {
7959              ftp_baton *baton = (ftp_baton*) req->data;
7960
7961              free(baton->host);
7962              // ...
7963              free(baton);
7964          }
7965
7966       We then free the baton which also frees the watcher.
7967
7968   External I/O with polling
7969       Usually third-party libraries will handle their own I/O, and keep track
7970       of their sockets and other files internally. In this case it isn't pos‐
7971       sible  to  use  the standard stream I/O operations, but the library can
7972       still be integrated into the libuv event loop. All that is required  is
7973       that  the  library  allow you to access the underlying file descriptors
7974       and provide functions that process tasks in small increments as decided
7975       by  your application. Some libraries though will not allow such access,
7976       providing only a standard blocking function which will perform the  en‐
7977       tire I/O transaction and only then return. It is unwise to use these in
7978       the event loop thread, use the Thread pool work scheduling instead.  Of
7979       course, this will also mean losing granular control on the library.
7980
7981       The  uv_poll section of libuv simply watches file descriptors using the
7982       operating system notification mechanism. In some sense, all the I/O op‐
7983       erations  that  libuv implements itself are also backed by uv_poll like
7984       code. Whenever the OS notices a change of state in file descriptors be‐
7985       ing polled, libuv will invoke the associated callback.
7986
7987       Here  we  will  walk  through  a  simple download manager that will use
7988       libcurl to download files. Rather than give  all  control  to  libcurl,
7989       we'll  instead be using the libuv event loop, and use the non-blocking,
7990       async multi interface to progress with the download whenever libuv  no‐
7991       tifies of I/O readiness.
7992
7993       uvwget/main.c - The setup
7994
7995          #include <assert.h>
7996          #include <stdio.h>
7997          #include <stdlib.h>
7998          #include <uv.h>
7999          #include <curl/curl.h>
8000
8001          uv_loop_t *loop;
8002          CURLM *curl_handle;
8003          uv_timer_t timeout;
8004          int main(int argc, char **argv) {
8005              loop = uv_default_loop();
8006
8007              if (argc <= 1)
8008                  return 0;
8009
8010              if (curl_global_init(CURL_GLOBAL_ALL)) {
8011                  fprintf(stderr, "Could not init cURL\n");
8012                  return 1;
8013              }
8014
8015              uv_timer_init(loop, &timeout);
8016
8017              curl_handle = curl_multi_init();
8018              curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket);
8019              curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout);
8020
8021              while (argc-- > 1) {
8022                  add_download(argv[argc], argc);
8023              }
8024
8025              uv_run(loop, UV_RUN_DEFAULT);
8026              curl_multi_cleanup(curl_handle);
8027              return 0;
8028          }
8029
8030
8031       The way each library is integrated with libuv will vary. In the case of
8032       libcurl, we can  register  two  callbacks.  The  socket  callback  han‐
8033       dle_socket  is  invoked  whenever  the state of a socket changes and we
8034       have to start polling it. start_timeout is called by libcurl to  notify
8035       us  of  the  next timeout interval, after which we should drive libcurl
8036       forward regardless of I/O status.  This is so that libcurl  can  handle
8037       errors or do whatever else is required to get the download moving.
8038
8039       Our downloader is to be invoked as:
8040
8041          $ ./uvwget [url1] [url2] ...
8042
8043       So we add each argument as a URL
8044
8045       uvwget/main.c - Adding urls
8046
8047
8048          void add_download(const char *url, int num) {
8049              char filename[50];
8050              sprintf(filename, "%d.download", num);
8051              FILE *file;
8052
8053              file = fopen(filename, "w");
8054              if (file == NULL) {
8055                  fprintf(stderr, "Error opening %s\n", filename);
8056                  return;
8057              }
8058
8059              CURL *handle = curl_easy_init();
8060              curl_easy_setopt(handle, CURLOPT_WRITEDATA, file);
8061              curl_easy_setopt(handle, CURLOPT_URL, url);
8062              curl_multi_add_handle(curl_handle, handle);
8063              fprintf(stderr, "Added download %s -> %s\n", url, filename);
8064          }
8065
8066
8067       We let libcurl directly write the data to a file, but much more is pos‐
8068       sible if you so desire.
8069
8070       start_timeout will be called immediately the first time by libcurl,  so
8071       things are set in motion. This simply starts a libuv timer which drives
8072       curl_multi_socket_action with  CURL_SOCKET_TIMEOUT  whenever  it  times
8073       out.  curl_multi_socket_action is what drives libcurl, and what we call
8074       whenever sockets change state. But before we go into that, we  need  to
8075       poll on sockets whenever handle_socket is called.
8076
8077       uvwget/main.c - Setting up polling
8078
8079
8080          void start_timeout(CURLM *multi, long timeout_ms, void *userp) {
8081              if (timeout_ms <= 0)
8082                  timeout_ms = 1; /* 0 means directly call socket_action, but we'll do it in a bit */
8083              uv_timer_start(&timeout, on_timeout, timeout_ms, 0);
8084          }
8085
8086          int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) {
8087              curl_context_t *curl_context;
8088              if (action == CURL_POLL_IN || action == CURL_POLL_OUT) {
8089                  if (socketp) {
8090                      curl_context = (curl_context_t*) socketp;
8091                  }
8092                  else {
8093                      curl_context = create_curl_context(s);
8094                      curl_multi_assign(curl_handle, s, (void *) curl_context);
8095                  }
8096              }
8097
8098              switch (action) {
8099                  case CURL_POLL_IN:
8100                      uv_poll_start(&curl_context->poll_handle, UV_READABLE, curl_perform);
8101                      break;
8102                  case CURL_POLL_OUT:
8103                      uv_poll_start(&curl_context->poll_handle, UV_WRITABLE, curl_perform);
8104                      break;
8105                  case CURL_POLL_REMOVE:
8106                      if (socketp) {
8107                          uv_poll_stop(&((curl_context_t*)socketp)->poll_handle);
8108                          destroy_curl_context((curl_context_t*) socketp);
8109                          curl_multi_assign(curl_handle, s, NULL);
8110                      }
8111                      break;
8112                  default:
8113                      abort();
8114              }
8115
8116              return 0;
8117          }
8118
8119
8120       We  are interested in the socket fd s, and the action. For every socket
8121       we create a uv_poll_t handle if it doesn't exist, and associate it with
8122       the socket using curl_multi_assign. This way socketp points to it when‐
8123       ever the callback is invoked.
8124
8125       In the case that the download is done or fails,  libcurl  requests  re‐
8126       moval of the poll. So we stop and free the poll handle.
8127
8128       Depending  on what events libcurl wishes to watch for, we start polling
8129       with UV_READABLE or UV_WRITABLE. Now libuv will invoke the  poll  call‐
8130       back  whenever  the  socket  is  ready  for reading or writing. Calling
8131       uv_poll_start multiple times on the same handle is acceptable, it  will
8132       just  update  the  events  mask with the new value. curl_perform is the
8133       crux of this program.
8134
8135       uvwget/main.c - Driving libcurl.
8136
8137          void curl_perform(uv_poll_t *req, int status, int events) {
8138              uv_timer_stop(&timeout);
8139              int running_handles;
8140              int flags = 0;
8141              if (status < 0)                      flags = CURL_CSELECT_ERR;
8142              if (!status && events & UV_READABLE) flags |= CURL_CSELECT_IN;
8143              if (!status && events & UV_WRITABLE) flags |= CURL_CSELECT_OUT;
8144
8145              curl_context_t *context;
8146
8147              context = (curl_context_t*)req;
8148
8149              curl_multi_socket_action(curl_handle, context->sockfd, flags, &running_handles);
8150              check_multi_info();
8151          }
8152
8153
8154       The first thing we do is to stop the timer, since there has  been  some
8155       progress  in  the  interval. Then depending on what event triggered the
8156       callback, we set the correct flags. Then we call  curl_multi_socket_ac‐
8157       tion with the socket that progressed and the flags informing about what
8158       events happened. At this point libcurl does all of its  internal  tasks
8159       in  small  increments,  and will attempt to return as fast as possible,
8160       which is exactly what an evented program  wants  in  its  main  thread.
8161       libcurl  keeps  queueing  messages  into  its  own queue about transfer
8162       progress. In our case we are only interested in transfers that are com‐
8163       pleted. So we extract these messages, and clean up handles whose trans‐
8164       fers are done.
8165
8166       uvwget/main.c - Reading transfer status.
8167
8168          void check_multi_info(void) {
8169              char *done_url;
8170              CURLMsg *message;
8171              int pending;
8172
8173              while ((message = curl_multi_info_read(curl_handle, &pending))) {
8174                  switch (message->msg) {
8175                  case CURLMSG_DONE:
8176                      curl_easy_getinfo(message->easy_handle, CURLINFO_EFFECTIVE_URL,
8177                                      &done_url);
8178                      printf("%s DONE\n", done_url);
8179
8180                      curl_multi_remove_handle(curl_handle, message->easy_handle);
8181                      curl_easy_cleanup(message->easy_handle);
8182                      break;
8183
8184                  default:
8185                      fprintf(stderr, "CURLMSG default\n");
8186                      abort();
8187                  }
8188              }
8189          }
8190
8191
8192   Check & Prepare watchers
8193       TODO
8194
8195   Loading libraries
8196       libuv provides a cross platform API  to  dynamically  load  shared  li‐
8197       braries.   This can be used to implement your own plugin/extension/mod‐
8198       ule system and is used by node.js to implement  require()  support  for
8199       bindings. The usage is quite simple as long as your library exports the
8200       right symbols. Be careful with sanity and security checks when  loading
8201       third  party  code,  otherwise  your program will behave unpredictably.
8202       This example implements a very simple plugin system which does  nothing
8203       except print the name of the plugin.
8204
8205       Let us first look at the interface provided to plugin authors.
8206
8207       plugin/plugin.h
8208
8209          #ifndef UVBOOK_PLUGIN_SYSTEM
8210          #define UVBOOK_PLUGIN_SYSTEM
8211
8212          // Plugin authors should use this to register their plugins with mfp.
8213          void mfp_register(const char *name);
8214
8215          #endif
8216
8217
8218       You  can similarly add more functions that plugin authors can use to do
8219       useful things in your application [2]. A sample plugin using  this  API
8220       is:
8221
8222       plugin/hello.c
8223
8224          #include "plugin.h"
8225
8226          void initialize() {
8227              mfp_register("Hello World!");
8228          }
8229
8230
8231       Our  interface defines that all plugins should have an initialize func‐
8232       tion which will be called by the application. This plugin  is  compiled
8233       as a shared library and can be loaded by running our application:
8234
8235          $ ./plugin libhello.dylib
8236          Loading libhello.dylib
8237          Registered plugin "Hello World!"
8238
8239       NOTE:
8240          The  shared  library  filename  will be different depending on plat‐
8241          forms. On Linux it is libhello.so.
8242
8243       This is done by using uv_dlopen to first load the shared  library  lib‐
8244       hello.dylib. Then we get access to the initialize function using uv_dl‐
8245       sym and invoke it.
8246
8247       plugin/main.c
8248
8249          #include "plugin.h"
8250
8251          typedef void (*init_plugin_function)();
8252
8253          void mfp_register(const char *name) {
8254              fprintf(stderr, "Registered plugin \"%s\"\n", name);
8255          }
8256
8257          int main(int argc, char **argv) {
8258              if (argc == 1) {
8259                  fprintf(stderr, "Usage: %s [plugin1] [plugin2] ...\n", argv[0]);
8260                  return 0;
8261              }
8262
8263              uv_lib_t *lib = (uv_lib_t*) malloc(sizeof(uv_lib_t));
8264              while (--argc) {
8265                  fprintf(stderr, "Loading %s\n", argv[argc]);
8266                  if (uv_dlopen(argv[argc], lib)) {
8267                      fprintf(stderr, "Error: %s\n", uv_dlerror(lib));
8268                      continue;
8269                  }
8270
8271                  init_plugin_function init_plugin;
8272                  if (uv_dlsym(lib, "initialize", (void **) &init_plugin)) {
8273                      fprintf(stderr, "dlsym error: %s\n", uv_dlerror(lib));
8274                      continue;
8275                  }
8276
8277                  init_plugin();
8278              }
8279
8280              return 0;
8281          }
8282
8283
8284       uv_dlopen expects a path to the shared  library  and  sets  the  opaque
8285       uv_lib_t  pointer. It returns 0 on success, -1 on error. Use uv_dlerror
8286       to get the error message.
8287
8288       uv_dlsym stores a pointer to the symbol in the second argument  in  the
8289       third  argument. init_plugin_function is a function pointer to the sort
8290       of function we are looking for in the application's plugins.
8291
8292   TTY
8293       Text terminals have supported basic formatting for a long time, with  a
8294       pretty  standardised command set. This formatting is often used by pro‐
8295       grams to improve the readability of terminal output. For  example  grep
8296       --colour.   libuv  provides the uv_tty_t abstraction (a stream) and re‐
8297       lated functions to implement the ANSI escape  codes  across  all  plat‐
8298       forms.  By  this  I  mean that libuv converts ANSI codes to the Windows
8299       equivalent, and provides functions to get terminal information.
8300
8301       The first thing to do is to initialize a uv_tty_t  with  the  file  de‐
8302       scriptor it reads/writes from. This is achieved with:
8303
8304          int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int unused)
8305
8306       The  unused  parameter  is now auto-detected and ignored. It previously
8307       needed to be set to use uv_read_start() on the stream.
8308
8309       It is then best to use uv_tty_set_mode to set the mode to normal  which
8310       enables  most  TTY  formatting,  flow-control and other settings. Other
8311       modes are also available.
8312
8313       Remember to call uv_tty_reset_mode when your program exits  to  restore
8314       the  state of the terminal. Just good manners. Another set of good man‐
8315       ners is to be aware of redirection. If the user redirects the output of
8316       your command to a file, control sequences should not be written as they
8317       impede readability and grep. To check if the file descriptor is  indeed
8318       a  TTY,  call  uv_guess_handle with the file descriptor and compare the
8319       return value with UV_TTY.
8320
8321       Here is a simple example which prints white text on a red background:
8322
8323       tty/main.c
8324
8325          #include <stdio.h>
8326          #include <string.h>
8327          #include <unistd.h>
8328          #include <uv.h>
8329
8330          uv_loop_t *loop;
8331          uv_tty_t tty;
8332          int main() {
8333              loop = uv_default_loop();
8334
8335              uv_tty_init(loop, &tty, STDOUT_FILENO, 0);
8336              uv_tty_set_mode(&tty, UV_TTY_MODE_NORMAL);
8337
8338              if (uv_guess_handle(1) == UV_TTY) {
8339                  uv_write_t req;
8340                  uv_buf_t buf;
8341                  buf.base = "\033[41;37m";
8342                  buf.len = strlen(buf.base);
8343                  uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL);
8344              }
8345
8346              uv_write_t req;
8347              uv_buf_t buf;
8348              buf.base = "Hello TTY\n";
8349              buf.len = strlen(buf.base);
8350              uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL);
8351              uv_tty_reset_mode();
8352              return uv_run(loop, UV_RUN_DEFAULT);
8353          }
8354
8355
8356       The final TTY helper is uv_tty_get_winsize() which is used to  get  the
8357       width  and  height  of the terminal and returns 0 on success. Here is a
8358       small program which does some animation using the function and  charac‐
8359       ter position escape codes.
8360
8361       tty-gravity/main.c
8362
8363          #include <stdio.h>
8364          #include <string.h>
8365          #include <unistd.h>
8366          #include <uv.h>
8367
8368          uv_loop_t *loop;
8369          uv_tty_t tty;
8370          uv_timer_t tick;
8371          uv_write_t write_req;
8372          int width, height;
8373          int pos = 0;
8374          char *message = "  Hello TTY  ";
8375
8376          void update(uv_timer_t *req) {
8377              char data[500];
8378
8379              uv_buf_t buf;
8380              buf.base = data;
8381              buf.len = sprintf(data, "\033[2J\033[H\033[%dB\033[%luC\033[42;37m%s",
8382                                      pos,
8383                                      (unsigned long) (width-strlen(message))/2,
8384                                      message);
8385              uv_write(&write_req, (uv_stream_t*) &tty, &buf, 1, NULL);
8386
8387              pos++;
8388              if (pos > height) {
8389                  uv_tty_reset_mode();
8390                  uv_timer_stop(&tick);
8391              }
8392          }
8393
8394          int main() {
8395              loop = uv_default_loop();
8396
8397              uv_tty_init(loop, &tty, STDOUT_FILENO, 0);
8398              uv_tty_set_mode(&tty, 0);
8399
8400              if (uv_tty_get_winsize(&tty, &width, &height)) {
8401                  fprintf(stderr, "Could not get TTY information\n");
8402                  uv_tty_reset_mode();
8403                  return 1;
8404              }
8405
8406              fprintf(stderr, "Width %d, height %d\n", width, height);
8407              uv_timer_init(loop, &tick);
8408              uv_timer_start(&tick, update, 200, 200);
8409              return uv_run(loop, UV_RUN_DEFAULT);
8410          }
8411
8412
8413       The escape codes are:
8414
8415                         ┌─────┬────────────────────────────┐
8416                         │Code │ Meaning                    │
8417                         ├─────┼────────────────────────────┤
84182 J  │ Clear  part of the screen, │
8419                         │     │ 2 is entire screen         │
8420                         ├─────┼────────────────────────────┤
8421                         │H    │ Moves  cursor  to  certain │
8422                         │     │ position, default top-left │
8423                         ├─────┼────────────────────────────┤
8424n B  │ Moves  cursor  down  by  n │
8425                         │     │ lines                      │
8426                         ├─────┼────────────────────────────┤
8427n C  │ Moves cursor  right  by  n │
8428                         │     │ columns                    │
8429                         ├─────┼────────────────────────────┤
8430                         │m    │ Obeys  string  of  display │
8431                         │     │ settings,  in  this   case │
8432                         │     │ green  background  (40+2), │
8433                         │     │ white text (30+7)          │
8434                         └─────┴────────────────────────────┘
8435
8436       As you can see this is very useful to produce nicely formatted  output,
8437       or  even  console  based  arcade  games if that tickles your fancy. For
8438       fancier control you can try ncurses.
8439
8440       Changed in version 1.23.1:: the readable parameter is  now  unused  and
8441       ignored.  The appropriate value will now be auto-detected from the ker‐
8442       nel.
8443
8444
8445
8446                                        ----
8447
8448
8449
8450       [1]  I was first introduced to the term baton in this context, in  Kon‐
8451            stantin  Käfer's  excellent  slides on writing node.js bindings --
8452            https://kkaefer.com/node-cpp-modules/#baton
8453
8454       [2]  mfp is My Fancy Plugin
8455
8456   About
8457       Nikhil Marathe started writing this book one afternoon (June 16,  2012)
8458       when he didn't feel like programming. He had recently been stung by the
8459       lack of good documentation on libuv while working on  node-taglib.  Al‐
8460       though reference documentation was present, there were no comprehensive
8461       tutorials. This book is the output of that need and tries to  be  accu‐
8462       rate.  That said, the book may have mistakes. Pull requests are encour‐
8463       aged.
8464
8465       Nikhil is indebted to Marc Lehmann's comprehensive man page about libev
8466       which describes much of the semantics of the two libraries.
8467
8468       This book was made using Sphinx and vim.
8469
8470       NOTE:
8471          In  2017  the  libuv project incorporated the Nikhil's work into the
8472          official documentation and it's maintained there henceforth.
8473
8474   Upgrading
8475       Migration guides for different libuv versions, starting with 1.0.
8476
8477   libuv 0.10 -> 1.0.0 migration guide
8478       Some APIs changed quite a bit throughout the 1.0.0 development process.
8479       Here  is  a  migration guide for the most significant changes that hap‐
8480       pened after 0.10 was released.
8481
8482   Loop initialization and closing
8483       In  libuv  0.10  (and  previous  versions),  loops  were  created  with
8484       uv_loop_new,  which allocated memory for a new loop and initialized it;
8485       and destroyed with uv_loop_delete, which destroyed the loop  and  freed
8486       the memory. Starting with 1.0, those are deprecated and the user is re‐
8487       sponsible for allocating the memory and then initializing the loop.
8488
8489       libuv 0.10
8490
8491          uv_loop_t* loop = uv_loop_new();
8492          ...
8493          uv_loop_delete(loop);
8494
8495       libuv 1.0
8496
8497          uv_loop_t* loop = malloc(sizeof *loop);
8498          uv_loop_init(loop);
8499          ...
8500          uv_loop_close(loop);
8501          free(loop);
8502
8503       NOTE:
8504          Error handling was omitted for brevity. Check the documentation  for
8505          uv_loop_init() and uv_loop_close().
8506
8507   Error handling
8508       Error handling had a major overhaul in libuv 1.0. In general, functions
8509       and status parameters would get 0 for success and  -1  for  failure  on
8510       libuv  0.10,  and  the user had to use uv_last_error to fetch the error
8511       code, which was a positive number.
8512
8513       In 1.0, functions and status parameters contain the actual error  code,
8514       which is 0 for success, or a negative number in case of error.
8515
8516       libuv 0.10
8517
8518          ... assume 'server' is a TCP server which is already listening
8519          r = uv_listen((uv_stream_t*) server, 511, NULL);
8520          if (r == -1) {
8521            uv_err_t err = uv_last_error(uv_default_loop());
8522            /* err.code contains UV_EADDRINUSE */
8523          }
8524
8525       libuv 1.0
8526
8527          ... assume 'server' is a TCP server which is already listening
8528          r = uv_listen((uv_stream_t*) server, 511, NULL);
8529          if (r < 0) {
8530            /* r contains UV_EADDRINUSE */
8531          }
8532
8533   Threadpool changes
8534       In  libuv  0.10  Unix  used  a threadpool which defaulted to 4 threads,
8535       while Windows used the QueueUserWorkItem API, which uses a Windows  in‐
8536       ternal threadpool, which defaults to 512 threads per process.
8537
8538       In  1.0,  we unified both implementations, so Windows now uses the same
8539       implementation Unix does. The threadpool size can be set  by  exporting
8540       the  UV_THREADPOOL_SIZE  environment  variable.  See  Thread  pool work
8541       scheduling.
8542
8543   Allocation callback API change
8544       In libuv 0.10 the callback had to return a filled uv_buf_t by value:
8545
8546          uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) {
8547              return uv_buf_init(malloc(size), size);
8548          }
8549
8550       In libuv 1.0 a pointer to a buffer is passed to the callback, which the
8551       user needs to fill:
8552
8553          void alloc_cb(uv_handle_t* handle, size_t size, uv_buf_t* buf) {
8554              buf->base = malloc(size);
8555              buf->len = size;
8556          }
8557
8558   Unification of IPv4 / IPv6 APIs
8559       libuv  1.0  unified  the  IPv4  and  IPv6  APIS.  There  is no longer a
8560       uv_tcp_bind and uv_tcp_bind6 duality, there is only uv_tcp_bind() now.
8561
8562       IPv4 functions took struct sockaddr_in structures by  value,  and  IPv6
8563       functions  took  struct sockaddr_in6. Now functions take a struct sock‐
8564       addr* (note it's a pointer).  It can be stack allocated.
8565
8566       libuv 0.10
8567
8568          struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", 1234);
8569          ...
8570          uv_tcp_bind(&server, addr)
8571
8572       libuv 1.0
8573
8574          struct sockaddr_in addr;
8575          uv_ip4_addr("0.0.0.0", 1234, &addr)
8576          ...
8577          uv_tcp_bind(&server, (const struct sockaddr*) &addr, 0);
8578
8579       The  IPv4  and  IPv6  struct  creating  functions  (uv_ip4_addr()   and
8580       uv_ip6_addr())  have  also  changed, make sure you check the documenta‐
8581       tion.
8582
8583       ..note::
8584              This change applies to all functions that made a distinction be‐
8585              tween IPv4 and IPv6 addresses.
8586
8587   Streams / UDP data receive callback API change
8588       The  streams  and  UDP  data  receive  callbacks now get a pointer to a
8589       uv_buf_t buffer, not a structure by value.
8590
8591       libuv 0.10
8592
8593          void on_read(uv_stream_t* handle,
8594                       ssize_t nread,
8595                       uv_buf_t buf) {
8596              ...
8597          }
8598
8599          void recv_cb(uv_udp_t* handle,
8600                       ssize_t nread,
8601                       uv_buf_t buf,
8602                       struct sockaddr* addr,
8603                       unsigned flags) {
8604              ...
8605          }
8606
8607       libuv 1.0
8608
8609          void on_read(uv_stream_t* handle,
8610                       ssize_t nread,
8611                       const uv_buf_t* buf) {
8612              ...
8613          }
8614
8615          void recv_cb(uv_udp_t* handle,
8616                       ssize_t nread,
8617                       const uv_buf_t* buf,
8618                       const struct sockaddr* addr,
8619                       unsigned flags) {
8620              ...
8621          }
8622
8623   Receiving handles over pipes API change
8624       In libuv 0.10 (and earlier versions) the  uv_read2_start  function  was
8625       used  to  start  reading data on a pipe, which could also result in the
8626       reception of handles over it. The callback  for  such  function  looked
8627       like this:
8628
8629          void on_read(uv_pipe_t* pipe,
8630                       ssize_t nread,
8631                       uv_buf_t buf,
8632                       uv_handle_type pending) {
8633              ...
8634          }
8635
8636       In  libuv  1.0, uv_read2_start was removed, and the user needs to check
8637       if  there  are  pending  handles  using   uv_pipe_pending_count()   and
8638       uv_pipe_pending_type() while in the read callback:
8639
8640          void on_read(uv_stream_t* handle,
8641                       ssize_t nread,
8642                       const uv_buf_t* buf) {
8643              ...
8644              while (uv_pipe_pending_count((uv_pipe_t*) handle) != 0) {
8645                  pending = uv_pipe_pending_type((uv_pipe_t*) handle);
8646                  ...
8647              }
8648              ...
8649          }
8650
8651   Extracting the file descriptor out of a handle
8652       While  it  wasn't  supported by the API, users often accessed the libuv
8653       internals in order to get access to the file descriptor of a  TCP  han‐
8654       dle, for example.
8655
8656          fd = handle->io_watcher.fd;
8657
8658       This is now properly exposed through the uv_fileno() function.
8659
8660   uv_fs_readdir rename and API change
8661       uv_fs_readdir  returned  a  list  of strings in the req->ptr field upon
8662       completion in  libuv  0.10.  In  1.0,  this  function  got  renamed  to
8663       uv_fs_scandir(), since it's actually implemented using scandir(3).
8664
8665       In  addition,  instead  of  allocating a full list strings, the user is
8666       able to get one result at a  time  by  using  the  uv_fs_scandir_next()
8667       function.  This  function  does  not  need  to  make a roundtrip to the
8668       threadpool, because libuv will keep the list of dents returned by scan‐
8669       dir(3) around.
8670

DOWNLOADS

8672       libuv can be downloaded from here.
8673

INSTALLATION

8675       Installation instructions can be found in the README.
8676

AUTHOR

8678       libuv contributors
8679
8681       2014-present, libuv contributors
8682
8683
8684
8685
86861.47.0                           Nov 16, 2023                         LIBUV(1)
Impressum