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