问题
Is it safe to invoke msgsnd
function from signal handler?
Code for our services is not intended to every gracefully complete, so I don't have exit point, however I need to send message to another process when services is stopped, so I need to catch SIGTERM and perform msgsnd
before calling exit(0).
Is that safe?
I looked into signal safety manual page and did not found msgsnd
in the list. Should I consider this as unsafe function? What are the possible consequences?
回答1:
No, it's not safe. (Note that exit()
doesn't appear on the async-signal-safe function list, either, though _exit()
does.)
msgsnd
might silently fail, might error out, might segfault, might hang forever, etc.
Consider refactoring a bit — if you need to do something upon SIGTERM then I'd say you do need graceful, or at least not clumsy, shutdown logic. If that's not feasible, perhaps SEM_UNDO can do what you want, as you seem to be comfortable with SysV IPC already. Or hold a file-system lock that is released upon process death. Or have the service parent catch SIGCHLD and then call msgsnd
. Etc.
来源:https://stackoverflow.com/questions/48304245/calling-sysv-msgsnd-from-signal-handler