Boost logo

Boost :

From: Ryan Gallagher (ryan.gallagher_at_[hidden])
Date: 2006-05-09 18:23:53


Stefan Seefeld <seefeld <at> sympatico.ca> writes:
> Aristid Breitkreuz wrote:
> > Am Dienstag, den 09.05.2006, 19:22 +0000 schrieb Ryan Gallagher:
> >> Out of curiousity, what is a good (portable?) way of dealing with signals
> >> in C++? C signal handling seems to force globals on you, which is a pain
> >> especially when signal handling is a late requirement.
> >
> > You might want to use a UNIX pipe for that (by calling pipe(2)). Just
> > write(2) into a pipe (less than PIPE_BUF bytes) and select(2) on it.
> > This is thread-safe and signal-safe and everything. Just not too speedy.
>
> I think semaphores are a widespread way to communicate from signal handlers
> back to a running program. They are reentrant, and their use involves less
> system calls than pipes, I believe.

Thanks for the replies and ideas, Aristid and Stefan. I'll definitely be
looking into them more when I have the chance. Actually, reading
dinkumware's C++ reference on sig_atomic_t seems to suggest a
semaphore-like approach. ( http://tinyurl.com/rbb8y )

> I don't think thinking of portable signal handling mechanisms is sensible,
> as signals themselves are (mostly) non-portable.

Yes, based upon my limited research, I have to agree with you on this.
I definitely agree if you replace your first "portable" with
"standard-compliant". (Portable is too vague a term I guess.) It doesn't
seem like there is much you can count upon accross systems. i.e. certain
system calls can't be called within a handler; exceptions can't been thrown
(portably); static's not of type volatile sig_atomic_t shouldn't be
referenced and those of that type only with atomic operations...

I do like being able to write:

signal_registry::instance().register_handler(SIGINT,
  bind(&database_test_monitor::handle_interruption_and_exit, cref(*this), _1));

which does work with msvc-7.1 (others?). It just seems more straight-forward
than polling a semaphore, especially in a program that isn't already designed
with this in mind. (But I can see an argument for having these explicit
signal handling points.)

Anyhow, what I like doesn't make it portable. I guess I'll have to
test and think about cases where this approach doesn't work before using
it on those system. I can always fall back to semaphores or pipes.

I'd still be interested in hearing cases where the code I've presented
(with some modifications) isn't portable in practice. I don't really imagine
that it would work on all systems and would be interested in learning from
cases where it doesn't. (In the very least I think that this code would need
a lock for the signal map to make it thread-safe.)

Thanks again for the replies based upon your experiences,

-Ryan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk