Isaac Fife
Isaac Fife

Reputation: 1690

How can I write cross platform c++ that handles signals?

This question is more for my personal curiosity than anything important. I'm trying to keep all my code compatible with at least Windows and Mac. So far I've learned that I should base my code on POSIX and that's just great but...

Windows doesn't have a sigaction function so signal is used? According to: What is the difference between sigaction and signal? there are some problems with signal.

  1. The signal() function does not block other signals from arriving while the current handler is executing; sigaction() can block other signals until the current handler returns.
  2. The signal() function resets the signal action back to SIG_DFL (default) for almost all signals. This means that the signal() handler must reinstall itself as its first action. It also opens up a window of vulnerability between the time when the signal is detected and the handler is reinstalled during which if a second instance of the signal arrives, the default behaviour (usually terminate, sometimes with prejudice - aka core dump) occurs.

If two SIGINT's come quickly then the application will terminate with default behavior. Is there any way to fix this behavior? What other implications do these two issues have on a process that, for instance wants to block SIGINT? Are there any other issues that I'm likely to run across while using signal? How do I fix them?

Upvotes: 4

Views: 4198

Answers (1)

paulsm4
paulsm4

Reputation: 121809

You really don't want to deal with signal()'s at all.

You want "events".

Ideally, you'll find a framework that's portable to all the main environments you wish to target - that would determine your choice of "event" implementation.

Here's an interesting thread that might help:

Game Objects Talking To Each Other

PS: The main difference between signal() and sigaction() is that sigaction() is "signal()" on steroids - more options, allows SA_RESTART, etc. I'd discourage using either one unless you really, really need to.

Upvotes: 5

Related Questions