Reputation: 1614
Are there any conventions/design pattern for using signals and signal handlers in a library code? Because signals are directed to the whole process and not to specific thread or library, i feel there may be some issues.
Let's say i m writing a shared library which will be used by other applications and i want to use alarm, setitimer functions and trap SIGALRM signal to do some processing at specific time.
I see some problems with it:
1) If application code (which i have no control of) also uses SIGALRM and i install my own signal handler for it, this may overwrite the application's signal handler and thus disable it's functionality. Of course i can make sure to call previous signal handler (retrieved by signal() function) from my own signal handler, but then there is still a reverse problem when application code can overwrite my signal handler and thus disable the functionality in my library.
2) Even worse than that, application developer may link with another shared library from another vendor which also uses SIGALRM, and thus nor me nor application developer would have any control over it.
3) Calling alarm() or setitimer() will overwrite the previous timer used by the process, so application could overwrite the timer i set in the library or vice versa.
I m kinda a novice at this, so i m wondering if there is already some convention for handling this? (For example, if every code is super nice, it would call previous signal handler from their own signal handler and also structure the alarm code to honor previous timers before overwriting them with their own timer)
Or should i avoid using signal handlers and alarm()s in a library alltogether?
Upvotes: 4
Views: 722
Reputation: 213829
Or should i avoid using signal handlers and alarm()s in a library alltogether?
Yes. For the reasons you've identified, you can't depend on signal disposition for anything, unless you control all code in the application.
You could document that your library requires that the application not use SIGALRM
, nor call alarm
, but the application developer may not have any control over that anyway, and so it's in your best interest to avoid placing such restrictions in the first place.
If your library can work without SIGALRM
(perhaps with reduced functionality), you can also make this feature optional, perhaps controlled by some environment variable. Then, if it is discovered that there is some code that interferes with your signal handling, you can tell the end-user to set your environment variable to disable that part of your library (which beats having to rebuild and supply a new version of it).
P.S. Your question and this answer applies to any library, whether shared or archive.
Upvotes: 5