2 * UCW Library -- Main Loop
4 * (c) 2004--2006 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include "ucw/mainloop.h"
27 ucw_time_t main_now_seconds;
28 timestamp_t main_idle_time;
31 clist main_timer_list, main_file_list, main_hook_list, main_process_list;
32 static uns main_file_cnt;
33 static uns main_poll_table_obsolete, main_poll_table_size;
34 static struct pollfd *main_poll_table;
35 static uns main_sigchld_set_up;
36 static volatile sig_atomic_t chld_received = 0;
39 // On recent Linux systems, O_CLOEXEC flag is available and we can get around
40 // the race condition of poll().
42 static int sig_pipe_recv, sig_pipe_send;
49 gettimeofday(&tv, NULL);
50 main_now_seconds = tv.tv_sec;
51 main_now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
52 // DBG("It's %lld o'clock", (long long) main_now);
58 DBG("MAIN: Initializing");
59 clist_init(&main_timer_list);
60 clist_init(&main_file_list);
61 clist_init(&main_hook_list);
62 clist_init(&main_process_list);
64 main_poll_table_obsolete = 1;
69 timer_add(struct main_timer *tm, timestamp_t expires)
72 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires-main_now));
74 DBG("MAIN: Clearing timer %p", tm);
77 tm->expires = expires;
80 cnode *t = main_timer_list.head.next;
81 while (t != &main_timer_list.head && ((struct main_timer *) t)->expires < expires)
83 clist_insert_before(&tm->n, t);
88 timer_del(struct main_timer *tm)
94 file_timer_expired(struct main_timer *tm)
96 struct main_file *fi = tm->data;
97 timer_del(&fi->timer);
98 if (fi->error_handler)
99 fi->error_handler(fi, MFERR_TIMEOUT);
103 file_add(struct main_file *fi)
105 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
107 clist_add_tail(&main_file_list, &fi->n);
108 fi->timer.handler = file_timer_expired;
111 main_poll_table_obsolete = 1;
112 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
113 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
117 file_chg(struct main_file *fi)
119 struct pollfd *p = fi->pollfd;
123 if (fi->read_handler)
124 p->events |= POLLIN | POLLHUP | POLLERR;
125 if (fi->write_handler)
126 p->events |= POLLOUT | POLLERR;
131 file_del(struct main_file *fi)
133 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
135 timer_del(&fi->timer);
136 clist_remove(&fi->n);
138 main_poll_table_obsolete = 1;
139 fi->n.next = fi->n.prev = NULL;
143 file_read_handler(struct main_file *fi)
145 while (fi->rpos < fi->rlen)
147 int l = read(fi->fd, fi->rbuf + fi->rpos, fi->rlen - fi->rpos);
148 DBG("MAIN: FD %d: read %d", fi->fd, l);
151 if (errno != EINTR && errno != EAGAIN && fi->error_handler)
152 fi->error_handler(fi, MFERR_READ);
159 DBG("MAIN: FD %d done read %d of %d", fi->fd, fi->rpos, fi->rlen);
160 fi->read_handler = NULL;
167 file_write_handler(struct main_file *fi)
169 while (fi->wpos < fi->wlen)
171 int l = write(fi->fd, fi->wbuf + fi->wpos, fi->wlen - fi->wpos);
172 DBG("MAIN: FD %d: write %d", fi->fd, l);
175 if (errno != EINTR && errno != EAGAIN && fi->error_handler)
176 fi->error_handler(fi, MFERR_WRITE);
181 DBG("MAIN: FD %d done write %d", fi->fd, fi->wpos);
182 fi->write_handler = NULL;
189 file_read(struct main_file *fi, void *buf, uns len)
194 fi->read_handler = file_read_handler;
201 fi->read_handler = NULL;
203 fi->rpos = fi->rlen = 0;
209 file_write(struct main_file *fi, void *buf, uns len)
214 fi->write_handler = file_write_handler;
221 fi->write_handler = NULL;
223 fi->wpos = fi->wlen = 0;
229 file_set_timeout(struct main_file *fi, timestamp_t expires)
232 timer_add(&fi->timer, expires);
238 CLIST_FOR_EACH(struct main_file *, f, main_file_list)
243 hook_add(struct main_hook *ho)
245 DBG("MAIN: Adding hook %p", ho);
247 clist_add_tail(&main_hook_list, &ho->n);
251 hook_del(struct main_hook *ho)
253 DBG("MAIN: Deleting hook %p", ho);
255 clist_remove(&ho->n);
256 ho->n.next = ho->n.prev = NULL;
261 main_sigchld_handler(int x UNUSED)
263 int old_errno = errno;
264 DBG("SIGCHLD received");
267 while((result = write(sig_pipe_send, "c", 1)) == -1 && errno == EINTR);
268 if(result == -1 && errno != EAGAIN)
269 msg(L_SIGHANDLER|L_ERROR, "Could not write to self-pipe: %m");
274 dummy_read_handler(struct main_file *mp)
277 ssize_t result = read(mp->fd, buffer, 1024);
278 if(result == -1 && errno != EAGAIN)
279 msg(L_ERROR, "Could not read from selfpipe: %m");
281 return result == 1024;
285 pipe_configure(int fd)
288 if((flags = fcntl(fd, F_GETFL)) == -1 || fcntl(fd, F_SETFL, flags|O_NONBLOCK))
289 die("Could not set file descriptor %d to non-blocking: %m", fd);
290 if((flags = fcntl(fd, F_GETFD)) == -1 || fcntl(fd, F_SETFD, flags|O_CLOEXEC))
291 die("Could not set file descriptor %d to close-on-exec: %m", fd);
295 main_sigchld_handler(int x UNUSED)
297 DBG("SIGCHLD received");
302 process_add(struct main_process *mp)
304 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
307 clist_add_tail(&main_process_list, &mp->n);
308 if (!main_sigchld_set_up)
312 if(pipe(pipe_result) == -1)
313 die("Could not create selfpipe:%m");
314 pipe_configure(pipe_result[0]);
315 pipe_configure(pipe_result[1]);
316 sig_pipe_recv = pipe_result[0];
317 sig_pipe_send = pipe_result[1];
318 static struct main_file self_pipe;
319 self_pipe = (struct main_file) {
321 .read_handler = dummy_read_handler
323 file_add(&self_pipe);
326 bzero(&sa, sizeof(sa));
327 sa.sa_handler = main_sigchld_handler;
328 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
329 sigaction(SIGCHLD, &sa, NULL);
330 main_sigchld_set_up = 1;
331 chld_received = 1; // The signal may have come before the handler
336 process_del(struct main_process *mp)
338 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
340 clist_remove(&mp->n);
345 process_fork(struct main_process *mp)
350 DBG("MAIN: Fork failed");
352 format_exit_status(mp->status_msg, -1);
360 DBG("MAIN: Forked process %d", (int) pid);
371 msg(L_DEBUG, "### Main loop status on %lld", (long long)main_now);
372 msg(L_DEBUG, "\tActive timers:");
373 struct main_timer *tm;
374 CLIST_WALK(tm, main_timer_list)
375 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires-main_now : 999999), tm->data);
376 struct main_file *fi;
377 msg(L_DEBUG, "\tActive files:");
378 CLIST_WALK(fi, main_file_list)
379 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, eh %p, expires %lld, data %p)",
380 fi, fi->fd, fi->read_handler, fi->write_handler, fi->error_handler,
381 (long long)(fi->timer.expires ? fi->timer.expires-main_now : 999999), fi->data);
382 msg(L_DEBUG, "\tActive hooks:");
383 struct main_hook *ho;
384 CLIST_WALK(ho, main_hook_list)
385 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
386 msg(L_DEBUG, "\tActive processes:");
387 struct main_process *pr;
388 CLIST_WALK(pr, main_process_list)
389 msg(L_DEBUG, "\t\t%p (pid %d, data %p)", pr, pr->pid, pr->data);
394 main_rebuild_poll_table(void)
396 struct main_file *fi;
397 if (main_poll_table_size < main_file_cnt)
400 xfree(main_poll_table);
402 main_poll_table_size = 1;
403 while (main_poll_table_size < main_file_cnt)
404 main_poll_table_size *= 2;
405 main_poll_table = xmalloc(sizeof(struct pollfd) * main_poll_table_size);
407 struct pollfd *p = main_poll_table;
408 DBG("MAIN: Rebuilding poll table: %d of %d entries set", main_file_cnt, main_poll_table_size);
409 CLIST_WALK(fi, main_file_list)
415 main_poll_table_obsolete = 0;
421 DBG("MAIN: Entering main_loop");
422 ASSERT(main_timer_list.head.next);
424 struct main_file *fi;
425 struct main_hook *ho;
426 struct main_timer *tm;
427 struct main_process *pr;
433 timestamp_t wake = main_now + 1000000000;
434 while ((tm = clist_head(&main_timer_list)) && tm->expires <= main_now)
436 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(main_now - tm->expires));
439 int hook_min = HOOK_RETRY;
440 int hook_max = HOOK_SHUTDOWN;
441 CLIST_WALK_DELSAFE(ho, main_hook_list, tmp)
443 DBG("MAIN: Hook %p", ho);
444 int ret = ho->handler(ho);
445 hook_min = MIN(hook_min, ret);
446 hook_max = MAX(hook_max, ret);
448 if (hook_min == HOOK_SHUTDOWN ||
449 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
452 DBG("MAIN: Shut down by %s", main_shutdown ? "main_shutdown" : "a hook");
455 if (hook_max == HOOK_RETRY)
457 if (main_poll_table_obsolete)
458 main_rebuild_poll_table();
459 #ifndef USE_SELF_PIPE
460 // We don't have a reliable flag without the self-pipe.
463 if (chld_received && !clist_empty(&main_process_list))
467 wake = MIN(wake, main_now + 10000);
469 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
471 DBG("MAIN: Child %d exited with status %x", pid, stat);
472 CLIST_WALK(pr, main_process_list)
477 format_exit_status(pr->status_msg, pr->status);
478 DBG("MAIN: Calling process exit handler");
485 if ((tm = clist_head(&main_timer_list)) && tm->expires < wake)
488 int timeout = (wake ? wake - main_now : 0);
489 DBG("MAIN: Poll for %d fds and timeout %d ms", main_file_cnt, timeout);
490 int p = poll(main_poll_table, main_file_cnt, timeout);
491 timestamp_t old_now = main_now;
493 main_idle_time += main_now - old_now;
496 struct pollfd *p = main_poll_table;
497 CLIST_WALK(fi, main_file_list)
499 if (p->revents & (POLLIN | POLLHUP | POLLERR))
502 DBG("MAIN: Read event on fd %d", p->fd);
503 while (fi->read_handler && fi->read_handler(fi) && !main_poll_table_obsolete);
504 if (main_poll_table_obsolete) /* File entries have been inserted or deleted => better not risk continuing to nowhere */
507 if (p->revents & (POLLOUT | POLLERR))
510 DBG("MAIN: Write event on fd %d", p->fd);
511 while (fi->write_handler && fi->write_handler(fi) && !main_poll_table_obsolete);
512 if (main_poll_table_obsolete)
523 static struct main_process mp;
524 static struct main_file fin, fout;
525 static struct main_hook hook;
526 static struct main_timer tm;
530 static void dread(struct main_file *fi)
532 if (fi->rpos < fi->rlen)
534 msg(L_INFO, "Read EOF");
539 msg(L_INFO, "Read done");
540 file_read(fi, rb, sizeof(rb));
544 static void derror(struct main_file *fi, int cause)
546 msg(L_INFO, "Error: %m !!! (cause %d)", cause);
550 static void dwrite(struct main_file *fi UNUSED)
552 msg(L_INFO, "Write done");
555 static int dhook(struct main_hook *ho UNUSED)
557 msg(L_INFO, "Hook called");
561 static void dtimer(struct main_timer *tm)
563 msg(L_INFO, "Timer tick");
564 timer_add(tm, main_now + 10000);
567 static void dentry(void)
569 msg(L_INFO, "*** SUBPROCESS START ***");
571 msg(L_INFO, "*** SUBPROCESS FINISH ***");
575 static void dexit(struct main_process *pr)
577 msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
587 fin.read_done = dread;
588 fin.error_handler = derror;
590 file_read(&fin, rb, sizeof(rb));
593 fout.write_done = dwrite;
594 fout.error_handler = derror;
596 file_write(&fout, "Hello, world!\n", 14);
598 hook.handler = dhook;
602 timer_add(&tm, main_now + 1000);
605 if (!process_fork(&mp))
611 msg(L_INFO, "Finished.");