]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.h
Xtype docs: Fixed a typo
[libucw.git] / ucw / mainloop.h
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2015 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #ifndef _UCW_MAINLOOP_H
11 #define _UCW_MAINLOOP_H
12
13 #include <ucw/clists.h>
14 #include <ucw/process.h>
15
16 #include <signal.h>
17
18 #ifdef CONFIG_UCW_CLEAN_ABI
19 #define block_io_add ucw_block_io_add
20 #define block_io_del ucw_block_io_del
21 #define block_io_read ucw_block_io_read
22 #define block_io_set_timeout ucw_block_io_set_timeout
23 #define block_io_write ucw_block_io_write
24 #define file_add ucw_file_add
25 #define file_chg ucw_file_chg
26 #define file_debug ucw_file_debug
27 #define file_del ucw_file_del
28 #define hook_add ucw_hook_add
29 #define hook_debug ucw_hook_debug
30 #define hook_del ucw_hook_del
31 #define main_cleanup ucw_main_cleanup
32 #define main_current ucw_main_current
33 #define main_debug_context ucw_main_debug_context
34 #define main_delete ucw_main_delete
35 #define main_destroy ucw_main_destroy
36 #define main_get_time ucw_main_get_time
37 #define main_init ucw_main_init
38 #define main_loop ucw_main_loop
39 #define main_new ucw_main_new
40 #define main_step ucw_main_step
41 #define main_switch_context ucw_main_switch_context
42 #define main_teardown ucw_main_teardown
43 #define process_add ucw_process_add
44 #define process_debug ucw_process_debug
45 #define process_del ucw_process_del
46 #define process_fork ucw_process_fork
47 #define rec_io_add ucw_rec_io_add
48 #define rec_io_del ucw_rec_io_del
49 #define rec_io_parse_line ucw_rec_io_parse_line
50 #define rec_io_set_timeout ucw_rec_io_set_timeout
51 #define rec_io_start_read ucw_rec_io_start_read
52 #define rec_io_stop_read ucw_rec_io_stop_read
53 #define rec_io_write ucw_rec_io_write
54 #define signal_add ucw_signal_add
55 #define signal_debug ucw_signal_debug
56 #define signal_del ucw_signal_del
57 #define timer_add ucw_timer_add
58 #define timer_add_rel ucw_timer_add_rel
59 #define timer_debug ucw_timer_debug
60 #define timer_del ucw_timer_del
61 #endif
62
63 /***
64  * [[basic]]
65  * Basic operations
66  * ----------------
67  *
68  * First of all, let us take a look at the basic operations with main loop contexts.
69  ***/
70
71 /** The main loop context **/
72 struct main_context {
73   timestamp_t now;                      /* [*] Current time in milliseconds since an unknown epoch. See main_get_time(). */
74   timestamp_t idle_time;                /* [*] Total time in milliseconds spent by waiting for events. */
75   uint shutdown;                                /* [*] Setting this to nonzero forces the main_loop() function to terminate. */
76   clist file_list;
77   clist file_active_list;
78   clist hook_list;
79   clist hook_done_list;
80   clist process_list;
81   clist signal_list;
82   uint file_cnt;
83   uint single_step;
84 #ifdef CONFIG_UCW_EPOLL
85   int epoll_fd;                         /* File descriptor used for epoll */
86   struct epoll_event *epoll_events;
87   clist file_recalc_list;
88 #else
89   uint poll_table_obsolete;
90   struct pollfd *poll_table;
91   struct main_file **poll_file_table;
92 #endif
93   uint poll_cnt;
94   struct main_timer **timer_table;      /* Growing array containing the heap of timers */
95   sigset_t want_signals;
96   int sig_pipe_send;
97   int sig_pipe_recv;
98   struct main_file *sig_pipe_file;
99   struct main_signal *sigchld_handler;
100 };
101
102 struct main_context *main_new(void);            /** Create a new context. **/
103
104 /**
105  * Delete a context, assuming it does have any event handlers attached. Does nothing if @m is NULL.
106  * It is allowed to call @main_delete() from a hook function of the same context, but you must
107  * never return to the main loop -- e.g., you can exit() the process instead.
108  **/
109 void main_delete(struct main_context *m);
110
111 /**
112  * Delete a context. If there are any event handlers attached, they are deactivated
113  * (but the responsibility to free the memory there were allocated from lies upon you).
114  * If there are any file handlers, the corresponding file descriptors are closed.
115  **/
116 void main_destroy(struct main_context *m);
117
118 /** Switch the current context of the calling thread. Returns the previous current context. **/
119 struct main_context *main_switch_context(struct main_context *m);
120
121 /** Return the current context. Dies if there is none or if the context has been deleted. **/
122 struct main_context *main_current(void);
123
124 /** Initialize the main loop module and create a top-level context. **/
125 void main_init(void);
126
127 /** Deinitialize the main loop module, calling @main_delete() on the top-level context. **/
128 void main_cleanup(void);
129
130 /**
131  * Deinitialize the main loop module, calling @main_destroy() on the top-level context.
132  * This is especially useful in a freshly forked-off child process.
133  **/
134 void main_teardown(void);
135
136 /**
137  * Start the event loop on the current context.
138  * It will watch the provided objects and call callbacks.
139  * Terminates when someone calls @main_shut_down(),
140  * or when all <<hook,hooks>> return <<enum_main_hook_return,`HOOK_DONE`>>
141  * or at last one <<hook,hook>> returns <<enum_main_hook_return,`HOOK_SHUTDOWN`>>.
142  **/
143 void main_loop(void);
144
145 /**
146  * Perform a single iteration of the main loop.
147  * Check if there are any events ready and process them.
148  * If there are none, do not wait.
149  **/
150 void main_step(void);
151
152 /** Ask the main loop to terminate at the nearest occasion. **/
153 static inline void main_shut_down(void)
154 {
155   main_current()->shutdown = 1;
156 }
157
158 /**
159  * Show the current state of a given context (use @main_debug() for the current context).
160  * Available only if LibUCW has been compiled with `CONFIG_UCW_DEBUG`.
161  **/
162 void main_debug_context(struct main_context *m);
163
164 static inline void main_debug(void)
165 {
166   main_debug_context(main_current());
167 }
168
169 /***
170  * [[time]]
171  * Timers
172  * ------
173  *
174  * The event loop provides the current time, measured as a 64-bit number
175  * of milliseconds since the system epoch (represented in the type `timestamp_t`).
176  *
177  * You can also register timers, which call a handler function at a given moment.
178  * The handler function must either call @timer_del() to delete the timer, or call
179  * @timer_add() with a different expiration time.
180  ***/
181
182 /**
183  * Get the current timestamp cached in the current context. It is refreshed in every
184  * iteration of the event loop, or explicitly by calling @main_get_time().
185  **/
186 static inline timestamp_t main_get_now(void)
187 {
188   return main_current()->now;
189 }
190
191 /**
192  * This is a description of a timer.
193  * You define the handler function and possibly user-defined data you wish
194  * to pass to the handler, and then you invoke @timer_add().
195  **/
196 struct main_timer {
197   cnode n;
198   timestamp_t expires;
199   uint index;
200   void (*handler)(struct main_timer *tm);       /* [*] Function to be called when the timer expires. */
201   void *data;                                   /* [*] Data for use by the handler */
202 };
203
204 /**
205  * Add a new timer into the main loop to be watched and called
206  * when it expires. It can also be used to modify an already running
207  * timer. It is permitted (and usual) to call this function from the
208  * timer's handler itself if you want the timer to trigger again.
209  *
210  * The @expire parameter is absolute (in the same time scale as @main_get_now()),
211  * use @timer_add_rel() for a relative version.
212  **/
213 void timer_add(struct main_timer *tm, timestamp_t expires);
214
215 /** Like @timer_add(), but the expiration time is relative to the current time. **/
216 void timer_add_rel(struct main_timer *tm, timestamp_t expires_delta);
217
218 /**
219  * Removes a timer from the active ones. It is permitted (and common) to call
220  * this function from the timer's handler itself if you want to deactivate
221  * the timer. Removing an already removed timer does nothing.
222  **/
223 void timer_del(struct main_timer *tm);
224
225 /** Tells whether a timer is running. **/
226 static inline int timer_is_active(struct main_timer *tm)
227 {
228   return !!tm->expires;
229 }
230
231 /**
232  * Forces refresh of the current timestamp cached in the active context.
233  * You usually do not need to call this, since it is called every time the
234  * loop polls for events. It is here if you need extra precision or some of the
235  * hooks takes a long time.
236  **/
237 void main_get_time(void);
238
239 /** Show current state of a timer. Available only if LibUCW has been compiled with `CONFIG_UCW_DEBUG`. **/
240 void timer_debug(struct main_timer *tm);
241
242 /***
243  * [[hooks]]
244  * Loop hooks
245  * ----------
246  *
247  * The hooks are called whenever the main loop performs an iteration.
248  * You can shutdown the main loop from within them or request an iteration
249  * to happen without sleeping (just poll, no waiting for events).
250  ***/
251
252 /**
253  * A hook. It contains the function to call and some user data.
254  *
255  * The handler() must return one value from
256  * <<enum_main_hook_return,`main_hook_return`>>.
257  *
258  * Fill with the hook and data and pass it to @hook_add().
259  **/
260 struct main_hook {
261   cnode n;
262   int (*handler)(struct main_hook *ho);         /* [*] Hook function; returns HOOK_xxx */
263   void *data;                                   /* [*] For use by the handler */
264 };
265
266 /**
267  * Return value of the hook handler().
268  * Specifies what should happen next.
269  *
270  * - `HOOK_IDLE` -- Let the loop sleep until something happens, call after that.
271  * - `HOOK_RETRY` -- Force the loop to perform another iteration without sleeping.
272  *   This will cause calling of all the hooks again soon.
273  * - `HOOK_DONE` -- The loop will terminate if all hooks return this.
274  * - `HOOK_SHUTDOWN` -- Shuts down the loop.
275  *
276  * The `HOOK_IDLE` and `HOOK_RETRY` constants are also used as return values
277  * of file handlers.
278  **/
279 enum main_hook_return {
280   HOOK_IDLE,
281   HOOK_RETRY,
282   HOOK_DONE = -1,
283   HOOK_SHUTDOWN = -2
284 };
285
286 /**
287  * Inserts a new hook into the loop.
288  * The hook will be scheduled at least once before next sleep.
289  * May be called from inside a hook handler too.
290  * Adding an already added hook is permitted and if the hook has been run,
291  * it will be run again before next sleep.
292  **/
293 void hook_add(struct main_hook *ho);
294
295 /**
296  * Removes an existing hook from the loop.
297  * May be called from inside a hook handler (to delete itself or another hook).
298  * Removing an already removed hook does nothing.
299  **/
300 void hook_del(struct main_hook *ho);
301
302 /** Tells if a hook is active (i.e., added). **/
303 static inline int hook_is_active(struct main_hook *ho)
304 {
305   return clist_is_linked(&ho->n);
306 }
307
308 /** Show current state of a hook. Available only if LibUCW has been compiled with `CONFIG_UCW_DEBUG`. **/
309 void hook_debug(struct main_hook *ho);
310
311
312 /***
313  * [[file]]
314  * Activity on file descriptors
315  * ----------------------------
316  *
317  * You can ask the main loop to watch a set of file descriptors for activity.
318  * (This is a generalization of the select() and poll() system calls. Internally,
319  * it uses either poll() or the more efficient epoll().)
320  *
321  * You create a <<struct_main_file,`struct main_file`>>, fill in a file descriptor
322  * and pointers to handler functions to be called when the descriptor becomes
323  * ready for reading and/or writing, and call @file_add(). When you need to
324  * modify the handlers (e.g., to set them to NULL if you are no longer interested
325  * in a given event), you should call @file_chg() to notify the main loop about
326  * the changes.
327  *
328  * From within the handler functions, you are allowed to call @file_chg() and even
329  * @file_del().
330  *
331  * The return value of a handler function should be either <<enum_main_hook_return,`HOOK_RETRY`>>
332  * or <<enum_main_hook_return,`HOOK_IDLE`>>. <<enum_main_hook_return,`HOOK_RETRY`>>
333  * signals that the function would like to consume more data immediately
334  * (i.e., it wants to be called again soon, but the event loop can postpone it after
335  * processing other events to avoid starvation). <<enum_main_hook_return,`HOOK_IDLE`>>
336  * tells that the handler wants to be called when the descriptor becomes ready again.
337  *
338  * For backward compatibility, 0 can be used instead of <<enum_main_hook_return,`HOOK_IDLE`>>
339  * and 1 for <<enum_main_hook_return,`HOOK_RETRY`>>.
340  *
341  * If you want to read/write fixed-size blocks of data asynchronously, the
342  * <<blockio,Asynchronous block I/O>> interface could be more convenient.
343  ***/
344
345 /**
346  * This structure describes a file descriptor to be watched and the handlers
347  * to be called when the descriptor is ready for reading and/or writing.
348  **/
349 struct main_file {
350   cnode n;
351   int fd;                                       /* [*] File descriptor */
352   int (*read_handler)(struct main_file *fi);    /* [*] To be called when ready for reading/writing; must call file_chg() afterwards */
353   int (*write_handler)(struct main_file *fi);
354   void *data;                                   /* [*] Data for use by the handlers */
355   uint events;
356   uint want_events;
357 #ifndef CONFIG_UCW_EPOLL
358   struct pollfd *pollfd;
359 #endif
360 };
361
362 /**
363  * Insert a <<struct_main_file,`main_file`>> structure into the main loop to be
364  * watched for activity. You can call this at any time, even inside a handler
365  * (of course for a different file descriptor than the one of the handler).
366  *
367  * The file descriptor is automatically set to the non-blocking mode.
368  **/
369 void file_add(struct main_file *fi);
370
371 /**
372  * Tell the main loop that the file structure has changed. Call it whenever you
373  * change any of the handlers.
374  *
375  * Can be called only on active files (only the ones added by @file_add()).
376  **/
377 void file_chg(struct main_file *fi);
378
379 /**
380  * Removes a file from the watched set. If you want to close a descriptor,
381  * please use this function first.
382  *
383  * Can be called from a handler.
384  * Removing an already removed file does nothing.
385  **/
386 void file_del(struct main_file *fi);
387
388 /** Tells if a file is active (i.e., added). **/
389 static inline int file_is_active(struct main_file *fi)
390 {
391   return clist_is_linked(&fi->n);
392 }
393
394 /** Show current state of a file. Available only if LibUCW has been compiled with `CONFIG_UCW_DEBUG`. **/
395 void file_debug(struct main_file *fi);
396
397 /***
398  * [[blockio]]
399  * Asynchronous block I/O
400  * ----------------------
401  *
402  * If you are reading or writing fixed-size blocks of data, you can let the
403  * block I/O interface handle the boring routine of handling partial reads
404  * and writes for you.
405  *
406  * You just create <<struct_main_block_io,`struct main_block_io`>> and call
407  * @block_io_add() on it, which sets up some <<struct_main_file,`main_file`>>s internally.
408  * Then you can just call @block_io_read() or @block_io_write() to ask for
409  * reading or writing of a given block. When the operation is finished,
410  * your handler function is called.
411  *
412  * Additionally, the block I/O is equipped with a timer, which can be used
413  * to detect communication timeouts. The timer is not touched internally
414  * (except that it gets added and deleted at the right places), feel free
415  * to adjust it from your handler functions by @block_io_set_timeout().
416  * When the timer expires, the error handler is automatically called with
417  * <<enum_block_io_err_cause,`BIO_ERR_TIMEOUT`>>.
418  ***/
419
420 /** The block I/O structure. **/
421 struct main_block_io {
422   struct main_file file;
423   byte *rbuf;                                   /* Read/write pointers for use by file_read/write */
424   uint rpos, rlen;
425   byte *wbuf;
426   uint wpos, wlen;
427   void (*read_done)(struct main_block_io *bio); /* [*] Called when file_read is finished; rpos < rlen if EOF */
428   void (*write_done)(struct main_block_io *bio);        /* [*] Called when file_write is finished */
429   void (*error_handler)(struct main_block_io *bio, int cause);  /* [*] Handler to call on errors */
430   struct main_timer timer;
431   void *data;                                   /* [*] Data for use by the handlers */
432 };
433
434 /** Activate a block I/O structure. **/
435 void block_io_add(struct main_block_io *bio, int fd);
436
437 /** Deactivate a block I/O structure. Calling twice is safe. **/
438 void block_io_del(struct main_block_io *bio);
439
440 /**
441  * Specifies when or why an error happened. This is passed to the error handler.
442  * `errno` is still set to the original source of error. The only exception
443  * is `BIO_ERR_TIMEOUT`, in which case `errno` is not set and the only possible
444  * cause of it is timeout of the timer associated with the block_io
445  * (see @block_io_set_timeout()).
446  **/
447 enum block_io_err_cause {
448   BIO_ERR_READ,
449   BIO_ERR_WRITE,
450   BIO_ERR_TIMEOUT
451 };
452
453 /**
454  * Ask the main loop to read @len bytes of data from @bio into @buf.
455  * It cancels any previous unfinished read requested in this way.
456  *
457  * When the read is done, the read_done() handler is called. If an EOF occurred,
458  * `rpos < rlen` (eg. not all data were read).
459  *
460  * Can be called from a handler.
461  *
462  * You can use a call with zero @len to cancel the current read, but all read data
463  * will be thrown away.
464  **/
465 void block_io_read(struct main_block_io *bio, void *buf, uint len);
466
467 /**
468  * Request that the main loop writes @len bytes of data from @buf to @bio.
469  * Cancels any previous unfinished write and overwrites `write_handler`.
470  *
471  * When it is written, the write_done() handler is called.
472  *
473  * Can be called from a handler.
474  *
475  * If you call it with zero @len, it will cancel the previous write, but note
476  * that some data may already be written.
477  **/
478 void block_io_write(struct main_block_io *bio, void *buf, uint len);
479
480 /**
481  * Sets a timer for a file @bio. If the timer is not overwritten or disabled
482  * until @expires_delta milliseconds, the file timeouts and error_handler() is called with
483  * <<enum_block_io_err_cause,`BIO_ERR_TIMEOUT`>>. A value of `0` stops the timer.
484  *
485  * Previous setting of the timeout on the same file will be overwritten.
486  *
487  * The use-cases for this are mainly sockets or pipes, when:
488  *
489  * - You want to drop inactive connections (no data comes in or out for a given time, not
490  *   incomplete messages).
491  * - You want to enforce answer in a given time (for example authentication).
492  * - Watching maximum time for a whole connection.
493  **/
494 void block_io_set_timeout(struct main_block_io *bio, timestamp_t expires_delta);
495
496 /** Tells if a @bio is active (i.e., added). **/
497 static inline int block_io_is_active(struct main_block_io *bio)
498 {
499   return file_is_active(&bio->file);
500 }
501
502 /***
503  * [[recordio]]
504  * Asynchronous record I/O
505  * -----------------------
506  *
507  * Record-based I/O is another front-end to the main loop file operations.
508  * Unlike its older cousin `main_block_io`, it is able to process records
509  * of variable length.
510  *
511  * To set it up, you create <<struct_main_rec_io,`struct main_rec_io`>> and call
512  * @rec_io_add() on it, which sets up some <<struct_main_file,`main_file`>>s internally.
513  *
514  * To read data from the file, call @rec_io_start_read() first. Whenever any data
515  * arrive from the file, they are appended to an internal buffer and the `read_handler`
516  * hook is called. The hook checks if the buffer already contains a complete record.
517  * If it is so, it processes the record and returns the number of bytes consumed.
518  * Otherwise, it returns 0 to tell the buffering machinery that more data are needed.
519  * When the read handler decides to destroy the `main_rec_io`, it must return `~0U`.
520  *
521  * On the write side, `main_rec_io` maintains a buffer keeping all data that should
522  * be written to the file. The @rec_io_write() function appends data to this buffer
523  * and it is written on background. A simple flow-control mechanism can be asked
524  * for: when more than `write_throttle_read` data are buffered for writing, reading
525  * is temporarily suspended.
526  *
527  * Additionally, the record I/O is equipped with a timer, which can be used
528  * to detect communication timeouts. The timer is not touched internally
529  * (except that it gets added and deleted at the right places), feel free
530  * to adjust it from your handler functions by @rec_io_set_timeout().
531  *
532  * All important events are passed to the `notify_handler`: errors when
533  * reading or writing, timeouts, the write buffer becoming empty, ... See
534  * <<enum_rec_io_notify_status,`enum rec_io_notify_status`>> for a complete list.
535  ***/
536
537 /** The record I/O structure. **/
538 struct main_rec_io {
539   struct main_file file;
540   byte *read_buf;
541   byte *read_rec_start;                         /* [*] Start of current record */
542   uint read_avail;                              /* [*] How much data is available */
543   uint read_prev_avail;                         /* [*] How much data was available in previous read_handler */
544   uint read_buf_size;                           /* [*] Read buffer size allocated (can be set before rec_io_add()) */
545   uint read_started;                            /* Reading requested by user */
546   uint read_running;                            /* Reading really runs (read_started && not stopped by write_throttle_read) */
547   uint read_rec_max;                            /* [*] Maximum record size (0=unlimited) */
548   clist busy_write_buffers;
549   clist idle_write_buffers;
550   uint write_buf_size;                          /* [*] Write buffer size allocated (can be set before rec_io_add()) */
551   uint write_watermark;                         /* [*] How much data are waiting to be written */
552   uint write_throttle_read;                     /* [*] If more than write_throttle_read bytes are buffered, stop reading; 0=no stopping */
553   uint (*read_handler)(struct main_rec_io *rio);        /* [*] Called whenever more bytes are read; returns 0 (want more) or number of bytes eaten */
554   int (*notify_handler)(struct main_rec_io *rio, int status);   /* [*] Called to notify about errors and other events */
555                                                 /* Returns either HOOK_RETRY or HOOK_IDLE. */
556   struct main_timer timer;
557   struct main_hook start_read_hook;             /* Used internally to defer rec_io_start_read() */
558   void *data;                                   /* [*] Data for use by the handlers */
559 };
560
561 /** Activate a record I/O structure. **/
562 void rec_io_add(struct main_rec_io *rio, int fd);
563
564 /** Deactivate a record I/O structure. Calling twice is safe. **/
565 void rec_io_del(struct main_rec_io *rio);
566
567 /**
568  * Start reading.
569  *
570  * When there were some data in the buffer (e.g., because @rec_io_stop_read()
571  * was called from the `read_handler`), it is processed as if it were read
572  * from the file once again. That is, `read_prev_avail` is reset to 0 and
573  * the `read_handler` is called to process all buffered data.
574  ***/
575 void rec_io_start_read(struct main_rec_io *rio);
576
577 /** Stop reading. **/
578 void rec_io_stop_read(struct main_rec_io *rio);
579
580 /** Analogous to @block_io_set_timeout(). **/
581 void rec_io_set_timeout(struct main_rec_io *rio, timestamp_t expires_delta);
582
583 void rec_io_write(struct main_rec_io *rio, void *data, uint len);
584
585 /**
586  * An auxiliary function used for parsing of lines. When called in the @read_handler,
587  * it searches for the end of line character. When a complete line is found, the length
588  * of the line (including the end of line character) is returned. Otherwise, it returns zero.
589  **/
590 uint rec_io_parse_line(struct main_rec_io *rio);
591
592 /**
593  * Specifies what kind of error or other event happened, when the @notify_handler
594  * is called. In case of I/O errors, `errno` is still set.
595  *
596  * Upon @RIO_ERR_READ, @RIO_ERR_RECORD_TOO_LARGE and @RIO_EVENT_EOF, reading is stopped
597  * automatically. Upon @RIO_ERR_WRITE, writing is stopped. Upon @RIO_ERR_TIMEOUT, only the
598  * timer is deactivated.
599  *
600  * In all cases, the notification handler is allowed to call @rec_io_del(), but it
601  * must return @HOOK_IDLE in such cases.
602  **/
603 enum rec_io_notify_status {
604   RIO_ERR_READ = -1,                    /* read() returned an error, errno set */
605   RIO_ERR_WRITE = -2,                   /* write() returned an error, errno set */
606   RIO_ERR_TIMEOUT = -3,                 /* A timeout has occurred */
607   RIO_ERR_RECORD_TOO_LARGE = -4,        /* Read: read_rec_max has been exceeded */
608   RIO_EVENT_ALL_WRITTEN = 1,            /* All buffered data has been written */
609   RIO_EVENT_PART_WRITTEN = 2,           /* Some buffered data has been written, but more remains */
610   RIO_EVENT_EOF = 3,                    /* Read: EOF seen */
611 };
612
613 /** Tells if a @rio is active (i.e., added). **/
614 static inline int rec_io_is_active(struct main_rec_io *rio)
615 {
616   return file_is_active(&rio->file);
617 }
618
619 /***
620  * [[process]]
621  * Child processes
622  * ---------------
623  *
624  * The main loop can watch child processes and notify you,
625  * when some of them terminates.
626  ***/
627
628 /**
629  * Description of a watched process.
630  * You fill in the handler() and `data`.
631  * The rest is set with @process_fork().
632  **/
633 struct main_process {
634   cnode n;
635   int pid;                                      /* Process id (0=not running) */
636   int status;                                   /* Exit status (-1=fork failed) */
637   char status_msg[EXIT_STATUS_MSG_SIZE];
638   void (*handler)(struct main_process *mp);     /* [*] Called when the process exits; process_del done automatically */
639   void *data;                                   /* [*] For use by the handler */
640 };
641
642 /**
643  * Asks the main loop to watch this process.
644  * As it is done automatically in @process_fork(), you need this only
645  * if you removed the process previously by @process_del().
646  **/
647 void process_add(struct main_process *mp);
648
649 /**
650  * Removes the process from the watched set. This is done
651  * automatically, when the process terminates, so you need it only
652  * when you do not want to watch a running process any more.
653  * Removing an already removed process does nothing.
654  */
655 void process_del(struct main_process *mp);
656
657 /**
658  * Forks and fills the @mp with information about the new process.
659  *
660  * If the fork() succeeds, it:
661  *
662  * - Returns 0 in the child.
663  * - Returns 1 in the parent and calls @process_add() on it.
664  *
665  * In the case of unsuccessful fork(), it:
666  *
667  * - Fills in the `status_msg` and sets `status` to -1.
668  * - Calls the handler() as if the process terminated.
669  * - Returns 1.
670  **/
671 int process_fork(struct main_process *mp);
672
673 /** Tells if a process is active (i.e., added). **/
674 static inline int process_is_active(struct main_process *mp)
675 {
676   return clist_is_linked(&mp->n);
677 }
678
679 /** Show current state of a process. Available only if LibUCW has been compiled with `CONFIG_UCW_DEBUG`. **/
680 void process_debug(struct main_process *pr);
681
682 /***
683  * [[signal]]
684  * Synchronous delivery of signals
685  * -------------------------------
686  *
687  * UNIX signals are delivered to processes in an asynchronous way: when a signal
688  * arrives (and it is not blocked), the process is interrupted and the corresponding
689  * signal handler function is called. However, most data structures and even most
690  * system library calls are not safe with respect to interrupts, so most program
691  * using signals contain subtle race conditions and may fail once in a long while.
692  *
693  * To avoid this problem, the event loop can be asked for synchronous delivery
694  * of signals. When a signal registered with @signal_add() arrives, it wakes up
695  * the loop (if it is not already awake) and it is processed in the same way
696  * as all other events.
697  *
698  * When used in a multi-threaded program, the signals are delivered to the thread
699  * which is currently using the particular main loop context. If the context is not
700  * current in any thread, the signals are blocked.
701  *
702  * As usually with UNIX signals, multiple instances of a single signal can be
703  * merged and delivered only once. (Some implementations of the main loop can even
704  * drop a signal completely during very intensive signal traffic, when an internal
705  * signal queue overflows.)
706  ***/
707
708 /** Description of a signal to catch. **/
709 struct main_signal {
710   cnode n;
711   int signum;                                   /* [*] Signal to catch */
712   void (*handler)(struct main_signal *ms);      /* [*] Called when the signal arrives */
713   void *data;                                   /* [*] For use by the handler */
714 };
715
716 /** Request a signal to be caught and delivered synchronously. **/
717 void signal_add(struct main_signal *ms);
718
719 /** Cancel a request for signal catching. Calling twice is safe. **/
720 void signal_del(struct main_signal *ms);
721
722 /** Tells if a signal catcher is active (i.e., added). **/
723 static inline int signal_is_active(struct main_signal *ms)
724 {
725   return clist_is_linked(&ms->n);
726 }
727
728 /** Show current state of a signal catcher. Available only if LibUCW has been compiled with `CONFIG_UCW_DEBUG`. **/
729 void signal_debug(struct main_signal *sg);
730
731 #endif