As we know, doing things in signal handlers is really bad, because they run in an interrupt-like context. It's quite possible that various

locks (including the malloc() heap lock!) are held when the signal handler is called.

The following methids will implement an async-siganl-safe timer on linux:


1. Use usleep(3) or sleep(3) in a single thread. This will block the thread until the timeout expires.

2. If you need to wait on I/O and have a timer expire before any I/O is ready, use select(2), poll(2) or epoll(7) with a timeout.

3. If you also need to use a signal handler, create a pipe with pipe(2), do a blocking read on the read side in a single thread, or use select/poll/epoll to wait for it to be ready, and write a byte to the write end of your pipe in the signal handler with write(2). It doesn't matter what you write to the pipe - the idea is to just get your thread to wake up. If you want to multiplex signals on the one pipe, write the signal number or some other ID to the pipe.

posted on 2009-05-20 18:38  njdragonfly  阅读(288)  评论(0编辑  收藏  举报