]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
561ddd3d691a1cdea055f9dc10a85482dd677d1a
[libucw.git] / ucw / mainloop.c
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2010 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 #undef LOCAL_DEBUG
11
12 #include "ucw/lib.h"
13 #include "ucw/heap.h"
14 #include "ucw/mainloop.h"
15 #include "ucw/threads.h"
16 #include "ucw/gary.h"
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <signal.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <sys/poll.h>
27 #include <sys/wait.h>
28 #include <sys/time.h>
29
30 #ifdef CONFIG_UCW_THREADS
31 #include <pthread.h>
32 #define THREAD_SIGMASK pthread_sigmask
33 #else
34 #define THREAD_SIGMASK sigprocmask
35 #endif
36
37 #ifdef CONFIG_UCW_EPOLL
38 #include <sys/epoll.h>
39 #endif
40
41 #define MAIN_TIMER_LESS(x,y) ((x)->expires < (y)->expires)
42 #define MAIN_TIMER_SWAP(heap,a,b,t) (t=heap[a], heap[a]=heap[b], heap[b]=t, heap[a]->index=(a), heap[b]->index=(b))
43
44 #define EPOLL_BUF_SIZE 256
45
46 static void
47 do_main_get_time(struct main_context *m)
48 {
49   struct timeval tv;
50   gettimeofday(&tv, NULL);
51   m->now_seconds = tv.tv_sec;
52   m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
53 }
54
55 struct main_context *
56 main_new(void)
57 {
58   struct main_context *m = xmalloc_zero(sizeof(*m));
59
60   DBG("MAIN: New context");
61   clist_init(&m->file_list);
62   clist_init(&m->file_active_list);
63   clist_init(&m->hook_list);
64   clist_init(&m->hook_done_list);
65   clist_init(&m->process_list);
66   clist_init(&m->signal_list);
67 #ifdef CONFIG_UCW_EPOLL
68   m->epoll_fd = epoll_create(64);
69   if (m->epoll_fd < 0)
70     die("epoll_create() failed: %m");
71   m->epoll_events = xmalloc(EPOLL_BUF_SIZE * sizeof(struct epoll_event *));
72   clist_init(&m->file_recalc_list);
73 #else
74   m->poll_table_obsolete = 1;
75 #endif
76   do_main_get_time(m);
77   sigemptyset(&m->want_signals);
78   m->sig_pipe_recv = m->sig_pipe_send = -1;
79
80   return m;
81 }
82
83 void
84 main_delete(struct main_context *m)
85 {
86   if (m->sigchld_handler)
87     signal_del(m->sigchld_handler);
88   if (m->sig_pipe_file)
89     file_del(m->sig_pipe_file);
90   if (m->sig_pipe_recv >= 0)
91     {
92       close(m->sig_pipe_recv);
93       close(m->sig_pipe_send);
94     }
95   ASSERT(clist_empty(&m->file_list));
96   ASSERT(clist_empty(&m->file_active_list));
97   ASSERT(clist_empty(&m->hook_list));
98   ASSERT(clist_empty(&m->hook_done_list));
99   ASSERT(clist_empty(&m->process_list));
100   ASSERT(clist_empty(&m->signal_list));
101   GARY_FREE(m->timer_table);
102 #ifdef CONFIG_UCW_EPOLL
103   ASSERT(clist_empty(&m->file_recalc_list));
104   xfree(m->epoll_events);
105   close(m->epoll_fd);
106 #else
107   GARY_FREE(m->poll_table);
108   GARY_FREE(m->poll_file_table);
109 #endif
110   xfree(m);
111   // FIXME: Some mechanism for cleaning up after fork()
112 }
113
114 struct main_context *
115 main_switch_context(struct main_context *m)
116 {
117   struct ucwlib_context *c = ucwlib_thread_context();
118   struct main_context *m0 = c->main_context;
119
120   /*
121    *  Not only we need to switch the signal sets of the two contexts,
122    *  but it is also necessary to avoid invoking a signal handler
123    *  in the middle of changing c->main_context.
124    */
125   if (m0 && !clist_empty(&m0->signal_list))
126     THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
127   c->main_context = m;
128   if (m && !clist_empty(&m->signal_list))
129     THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
130
131   return m0;
132 }
133
134 struct main_context *
135 main_current(void)
136 {
137   struct ucwlib_context *c = ucwlib_thread_context();
138   struct main_context *m = c->main_context;
139   ASSERT(m);
140   return m;
141 }
142
143 void
144 main_init(void)
145 {
146   struct main_context *m = main_switch_context(main_new());
147   ASSERT(!m);
148 }
149
150 void
151 main_cleanup(void)
152 {
153   struct main_context *m = main_switch_context(NULL);
154   main_delete(m);
155 }
156
157 void
158 main_get_time(void)
159 {
160   do_main_get_time(main_current());
161 }
162
163 static inline uns
164 count_timers(struct main_context *m)
165 {
166   return GARY_SIZE(m->timer_table) - 1;
167 }
168
169 void
170 timer_add(struct main_timer *tm, timestamp_t expires)
171 {
172   struct main_context *m = main_current();
173
174   if (!m->timer_table)
175     {
176       GARY_INIT(m->timer_table, 1);
177       m->timer_table[0] = NULL;
178     }
179
180   if (expires)
181     DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
182   else
183     DBG("MAIN: Clearing timer %p", tm);
184   uns num_timers = count_timers(m);
185   if (tm->expires < expires)
186     {
187       if (!tm->expires)
188         {
189           tm->expires = expires;
190           tm->index = num_timers + 1;
191           *GARY_PUSH(m->timer_table, 1) = tm;
192           HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
193         }
194       else
195         {
196           tm->expires = expires;
197           HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
198         }
199     }
200   else if (tm->expires > expires)
201     {
202       if (!expires)
203         {
204           ASSERT(tm->index && tm->index <= num_timers);
205           HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
206           tm->index = 0;
207           tm->expires = 0;
208           GARY_POP(m->timer_table, 1);
209         }
210       else
211         {
212           tm->expires = expires;
213           HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
214         }
215     }
216 }
217
218 void
219 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
220 {
221   struct main_context *m = main_current();
222   return timer_add(tm, m->now + expires_delta);
223 }
224
225 void
226 timer_del(struct main_timer *tm)
227 {
228   timer_add(tm, 0);
229 }
230
231 static uns
232 file_want_events(struct main_file *fi)
233 {
234   uns events = 0;
235   if (fi->read_handler)
236     events |= POLLIN | POLLHUP | POLLERR;
237   if (fi->write_handler)
238     events |= POLLOUT | POLLERR;
239   return events;
240 }
241
242 void
243 file_add(struct main_file *fi)
244 {
245   struct main_context *m = main_current();
246
247   DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
248   ASSERT(!clist_is_linked(&fi->n));
249   clist_add_tail(&m->file_list, &fi->n);
250   m->file_cnt++;
251 #ifdef CONFIG_UCW_EPOLL
252   struct epoll_event evt = {
253     .events = file_want_events(fi),
254     .data.ptr = fi,
255   };
256   if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, fi->fd, &evt) < 0)
257     die("epoll_ctl() failed: %m");
258   fi->last_want_events = evt.events;
259 #else
260   m->poll_table_obsolete = 1;
261 #endif
262   if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
263     msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
264 }
265
266 void
267 file_chg(struct main_file *fi)
268 {
269 #ifdef CONFIG_UCW_EPOLL
270   clist_remove(&fi->n);
271   clist_add_tail(&main_current()->file_recalc_list, &fi->n);
272 #else
273   struct pollfd *p = fi->pollfd;
274   if (p)
275     p->events = file_want_events(fi);
276 #endif
277 }
278
279 void
280 file_del(struct main_file *fi)
281 {
282   struct main_context *m = main_current();
283
284   DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
285   ASSERT(clist_is_linked(&fi->n));
286   clist_unlink(&fi->n);
287   m->file_cnt--;
288 #ifdef CONFIG_UCW_EPOLL
289   if (epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
290     die("epoll_ctl() failed: %m");
291 #else
292   m->poll_table_obsolete = 1;
293 #endif
294 }
295
296 void
297 file_close_all(void)
298 {
299   struct main_context *m = main_current();
300
301   CLIST_FOR_EACH(struct main_file *, f, m->file_list)
302     close(f->fd);
303 }
304
305 void
306 hook_add(struct main_hook *ho)
307 {
308   struct main_context *m = main_current();
309
310   DBG("MAIN: Adding hook %p", ho);
311   ASSERT(!clist_is_linked(&ho->n));
312   clist_add_tail(&m->hook_list, &ho->n);
313 }
314
315 void
316 hook_del(struct main_hook *ho)
317 {
318   DBG("MAIN: Deleting hook %p", ho);
319   ASSERT(clist_is_linked(&ho->n));
320   clist_unlink(&ho->n);
321 }
322
323 static void
324 sigchld_received(struct main_signal *sg UNUSED)
325 {
326   struct main_context *m = main_current();
327   int stat;
328   pid_t pid;
329
330   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
331     {
332       DBG("MAIN: Child %d exited with status %x", pid, stat);
333       CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
334         if (pr->pid == pid)
335           {
336             pr->status = stat;
337             process_del(pr);
338             format_exit_status(pr->status_msg, pr->status);
339             DBG("MAIN: Calling process exit handler");
340             pr->handler(pr);
341             break;
342           }
343     }
344 }
345
346 void
347 process_add(struct main_process *mp)
348 {
349   struct main_context *m = main_current();
350
351   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
352   ASSERT(!clist_is_linked(&mp->n));
353   ASSERT(mp->handler);
354   clist_add_tail(&m->process_list, &mp->n);
355   if (!m->sigchld_handler)
356     {
357       struct main_signal *sg = xmalloc_zero(sizeof(*sg));
358       m->sigchld_handler = sg;
359       sg->signum = SIGCHLD;
360       sg->handler = sigchld_received;
361       signal_add(sg);
362     }
363 }
364
365 void
366 process_del(struct main_process *mp)
367 {
368   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
369   ASSERT(clist_is_linked(&mp->n));
370   clist_unlink(&mp->n);
371 }
372
373 int
374 process_fork(struct main_process *mp)
375 {
376   pid_t pid = fork();
377   if (pid < 0)
378     {
379       DBG("MAIN: Fork failed");
380       mp->status = -1;
381       format_exit_status(mp->status_msg, -1);
382       mp->handler(mp);
383       return 1;
384     }
385   else if (!pid)
386     return 0;
387   else
388     {
389       DBG("MAIN: Forked process %d", (int) pid);
390       mp->pid = pid;
391       process_add(mp);
392       return 1;
393     }
394 }
395
396 static int
397 pipe_read_handler(struct main_file *mf UNUSED)
398 {
399   struct main_context *m = main_current();
400   int signum;
401   int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
402
403   if (n < 0)
404     {
405       if (errno != EAGAIN)
406         msg(L_ERROR, "Error reading signal pipe: %m");
407       return 0;
408     }
409   ASSERT(n == sizeof(signum));
410
411   DBG("MAIN: Sigpipe: received signal %d", signum);
412   struct main_signal iter = { .signum = -1 };
413   struct main_signal *sg = clist_head(&m->signal_list);
414   while (sg)
415     {
416       if (sg->signum == signum)
417         {
418           DBG("MAIN: Sigpipe: invoking handler %p", sg);
419           clist_insert_after(&iter.n, &sg->n);
420           sg->handler(sg);
421           sg = clist_next(&m->signal_list, &iter.n);
422           clist_remove(&iter.n);
423         }
424       else
425         sg = clist_next(&m->signal_list, &sg->n);
426     }
427
428   return 1;
429 }
430
431 static void
432 pipe_configure(int fd)
433 {
434   int flags;
435   if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
436     die("Could not set file descriptor %d to non-blocking: %m", fd);
437 }
438
439 static void
440 pipe_setup(struct main_context *m)
441 {
442   DBG("MAIN: Sigpipe: Setting up the pipe");
443
444   int pipe_result[2];
445   if (pipe(pipe_result) == -1)
446     die("Could not create signal pipe: %m");
447   pipe_configure(pipe_result[0]);
448   pipe_configure(pipe_result[1]);
449   m->sig_pipe_recv = pipe_result[0];
450   m->sig_pipe_send = pipe_result[1];
451
452   struct main_file *f = xmalloc_zero(sizeof(*f));
453   m->sig_pipe_file = f;
454   f->fd = m->sig_pipe_recv;
455   f->read_handler = pipe_read_handler;
456   file_add(f);
457 }
458
459 static void
460 signal_handler_pipe(int signum)
461 {
462   struct main_context *m = main_current();
463 #ifdef LOCAL_DEBUG
464   msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
465 #endif
466   write(m->sig_pipe_send, &signum, sizeof(signum));
467 }
468
469 void
470 signal_add(struct main_signal *ms)
471 {
472   struct main_context *m = main_current();
473
474   DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
475
476   ASSERT(!clist_is_linked(&ms->n));
477   // Adding at the head of the list is better if we are in the middle of walking the list.
478   clist_add_head(&m->signal_list, &ms->n);
479   if (m->sig_pipe_recv < 0)
480     pipe_setup(m);
481
482   struct sigaction sa = {
483     .sa_handler = signal_handler_pipe,
484     .sa_flags = SA_NOCLDSTOP | SA_RESTART,
485   };
486   sigaction(ms->signum, &sa, NULL);
487
488   sigset_t ss;
489   sigemptyset(&ss);
490   sigaddset(&ss, ms->signum);
491   THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
492   sigaddset(&m->want_signals, ms->signum);
493 }
494
495 void
496 signal_del(struct main_signal *ms)
497 {
498   struct main_context *m = main_current();
499
500   DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
501
502   ASSERT(clist_is_linked(&ms->n));
503   clist_unlink(&ms->n);
504
505   int another = 0;
506   CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
507     if (s->signum == ms->signum)
508       another++;
509   if (!another)
510     {
511       sigset_t ss;
512       sigemptyset(&ss);
513       sigaddset(&ss, ms->signum);
514       THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
515       sigdelset(&m->want_signals, ms->signum);
516     }
517 }
518
519 void
520 main_debug_context(struct main_context *m UNUSED)
521 {
522 #ifdef CONFIG_DEBUG
523   msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
524   msg(L_DEBUG, "\tActive timers:");
525   uns num_timers = count_timers(m);
526   for (uns i = 1; i <= num_timers; i++)
527     {
528       struct main_timer *tm = m->timer_table[i];
529       msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
530     }
531   msg(L_DEBUG, "\tActive files:");
532   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
533     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
534         fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
535   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
536     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending events: %x]",
537         fi, fi->fd, fi->read_handler, fi->write_handler, fi->data, fi->events);
538     // FIXME: Can we display status of block_io requests somehow?
539 #ifdef CONFIG_UCW_EPOLL
540   CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
541     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending recalculation]",
542         fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
543 #endif
544   msg(L_DEBUG, "\tActive hooks:");
545   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
546     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
547   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
548     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
549   msg(L_DEBUG, "\tActive processes:");
550   CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
551     msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
552   msg(L_DEBUG, "\tActive signal catchers:");
553   CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
554     if (sg->signum < 0)
555       msg(L_DEBUG, "\t\t(placeholder)");
556     else
557       msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
558 #endif
559 }
560
561 static void
562 process_timers(struct main_context *m)
563 {
564   struct main_timer *tm;
565   while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
566     {
567       DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
568       tm->handler(tm);
569     }
570 }
571
572 static enum main_hook_return
573 process_hooks(struct main_context *m)
574 {
575   int hook_min = HOOK_RETRY;
576   int hook_max = HOOK_SHUTDOWN;
577   struct main_hook *ho;
578
579   while (ho = clist_remove_head(&m->hook_list))
580     {
581       clist_add_tail(&m->hook_done_list, &ho->n);
582       DBG("MAIN: Hook %p", ho);
583       int ret = ho->handler(ho);
584       hook_min = MIN(hook_min, ret);
585       hook_max = MAX(hook_max, ret);
586     }
587   clist_move(&m->hook_list, &m->hook_done_list);
588   if (hook_min == HOOK_SHUTDOWN ||
589     hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
590     m->shutdown)
591     {
592       DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
593       return HOOK_SHUTDOWN;
594     }
595   if (hook_max == HOOK_RETRY)
596     return HOOK_RETRY;
597   else
598     return HOOK_IDLE;
599 }
600
601 #ifdef CONFIG_UCW_EPOLL
602
603 static void
604 recalc_files(struct main_context *m)
605 {
606   struct main_file *fi;
607
608   while (fi = clist_remove_head(&m->file_recalc_list))
609     {
610       struct epoll_event evt = {
611         .events = file_want_events(fi),
612         .data.ptr = fi,
613       };
614       if (evt.events != fi->last_want_events)
615         {
616           DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
617           fi->last_want_events = evt.events;
618           if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
619             die("epoll_ctl() failed: %m");
620         }
621       clist_add_tail(&m->file_list, &fi->n);
622     }
623 }
624
625 #else
626
627 static void
628 rebuild_poll_table(struct main_context *m)
629 {
630   GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
631   GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
632   DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
633
634   struct pollfd *p = m->poll_table;
635   struct main_file **pf = m->poll_file_table;
636   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
637     {
638       p->fd = fi->fd;
639       p->events = file_want_events(fi);
640       fi->pollfd = p++;
641       *pf++ = fi;
642     }
643   m->poll_table_obsolete = 0;
644 }
645
646 #endif
647
648 void
649 main_loop(void)
650 {
651   DBG("MAIN: Entering main_loop");
652   struct main_context *m = main_current();
653
654   do_main_get_time(m);
655   for (;;)
656     {
657       timestamp_t wake = m->now + 1000000000;
658       process_timers(m);
659       switch (process_hooks(m))
660         {
661         case HOOK_SHUTDOWN:
662           return;
663         case HOOK_RETRY:
664           wake = 0;
665           break;
666         default: ;
667         }
668       if (count_timers(m))
669         wake = MIN(wake, m->timer_table[1]->expires);
670       do_main_get_time(m);
671       int timeout = ((wake > m->now) ? wake - m->now : 0);
672
673 #ifdef CONFIG_UCW_EPOLL
674       recalc_files(m);
675       DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
676       int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
677 #else
678       if (m->poll_table_obsolete)
679         rebuild_poll_table(m);
680       DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
681       int n = poll(m->poll_table, m->file_cnt, timeout);
682 #endif
683
684       DBG("\t-> %d events", n);
685       if (n < 0 && errno != EAGAIN && errno != EINTR)
686         die("(e)poll failed: %m");
687       timestamp_t old_now = m->now;
688       do_main_get_time(m);
689       m->idle_time += m->now - old_now;
690
691       if (n <= 0)
692         continue;
693
694       // Relink all files with a pending event to file_active_list
695 #ifdef CONFIG_UCW_EPOLL
696       for (int i=0; i<n; i++)
697         {
698           struct epoll_event *e = &m->epoll_events[i];
699           struct main_file *fi = e->data.ptr;
700           clist_remove(&fi->n);
701           clist_add_tail(&m->file_active_list, &fi->n);
702           fi->events = e->events;
703         }
704 #else
705       struct pollfd *p = m->poll_table;
706       struct main_file **pf = m->poll_file_table;
707       for (uns i=0; i < m->file_cnt; i++)
708         if (p[i].revents)
709           {
710             struct main_file *fi = pf[i];
711             clist_remove(&fi->n);
712             clist_add_tail(&m->file_active_list, &fi->n);
713             fi->events = p[i].revents;
714           }
715 #endif
716
717       // Process the buffered file events
718       struct main_file *fi;
719       while (fi = clist_remove_head(&m->file_active_list))
720         {
721           clist_add_tail(&m->file_list, &fi->n);
722           if (fi->events & (POLLIN | POLLHUP | POLLERR))
723             {
724               do
725                 DBG("MAIN: Read event on fd %d", fi->fd);
726               while (fi->read_handler && fi->read_handler(fi));
727             }
728           if (fi->events & (POLLOUT | POLLERR))
729             {
730               do
731                 DBG("MAIN: Write event on fd %d", fi->fd);
732               while (fi->write_handler && fi->write_handler(fi));
733             }
734         }
735     }
736 }
737
738 #ifdef TEST
739
740 static struct main_process mp;
741 static struct main_block_io fin, fout;
742 static struct main_hook hook;
743 static struct main_timer tm;
744 static struct main_signal sg;
745
746 static byte rb[16];
747
748 static void dread(struct main_block_io *bio)
749 {
750   if (bio->rpos < bio->rlen)
751     {
752       msg(L_INFO, "Read EOF");
753       block_io_del(bio);
754     }
755   else
756     {
757       msg(L_INFO, "Read done");
758       block_io_read(bio, rb, sizeof(rb));
759     }
760 }
761
762 static void derror(struct main_block_io *bio, int cause)
763 {
764   msg(L_INFO, "Error: %m !!! (cause %d)", cause);
765   block_io_del(bio);
766 }
767
768 static void dwrite(struct main_block_io *bio UNUSED)
769 {
770   msg(L_INFO, "Write done");
771 }
772
773 static int dhook(struct main_hook *ho UNUSED)
774 {
775   msg(L_INFO, "Hook called");
776   return 0;
777 }
778
779 static void dtimer(struct main_timer *tm)
780 {
781   msg(L_INFO, "Timer tick");
782   timer_add_rel(tm, 11000);
783   timer_add_rel(tm, 10000);
784 }
785
786 static void dentry(void)
787 {
788   msg(L_INFO, "*** SUBPROCESS START ***");
789   sleep(2);
790   msg(L_INFO, "*** SUBPROCESS FINISH ***");
791   exit(0);
792 }
793
794 static void dexit(struct main_process *pr)
795 {
796   msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
797 }
798
799 static void dsignal(struct main_signal *sg UNUSED)
800 {
801   msg(L_INFO, "SIGINT received (use Ctrl-\\ to really quit)");
802 }
803
804 int
805 main(void)
806 {
807   log_init(NULL);
808   main_init();
809
810   fin.read_done = dread;
811   fin.error_handler = derror;
812   block_io_add(&fin, 0);
813   block_io_read(&fin, rb, sizeof(rb));
814
815   fout.write_done = dwrite;
816   fout.error_handler = derror;
817   block_io_add(&fout, 1);
818   block_io_write(&fout, "Hello, world!\n", 14);
819
820   hook.handler = dhook;
821   hook_add(&hook);
822
823   tm.handler = dtimer;
824   timer_add_rel(&tm,  1000);
825
826   sg.signum = SIGINT;
827   sg.handler = dsignal;
828   signal_add(&sg);
829
830   mp.handler = dexit;
831   if (!process_fork(&mp))
832     dentry();
833
834   main_debug();
835
836   main_loop();
837   msg(L_INFO, "Finished.");
838 }
839
840 #endif