问题
I am developing for Linux and have a daemon that should write to disk when it is killed. The daemon could be configured to listen to SIGTERM
and write to disk when that signal is received.
I am also familiar with the PrepareForShutdown
D-Bus signal issued by the login manager. Listening to SIGTERM
results in simpler code than inhibiting shutdown and listening to the PrepareForShutdown
signal. Another advantage of SIGTERM
is that it handles cases where the daemon is politely killed even though the system shuts down.
However, I am not sure how safe it is to rely on the SIGTERM
signal being sent by the kernel at shutdown. At shutdown is SIGTERM
always sent to every process with enough time to perform a small (< 1 kB) write to disk?
One concern I have is that I might have enough time to write to disk on some hardware but not on others, so it seems difficult to test. The same could be said of the PrepareForShutdown
signal, but at least allowing enough time for disk writes is part of the contract of that signal. My question is whether the same can be said for the SIGTERM
signal every process receives on shutdown.
回答1:
Read carefully signal(7) - so you can't fprintf
from a signal handler. Often the most sensible thing to do is to set some volatile sigatomic_t
variable in the signal handler, and test that variable outside it.
The point is not only to write(2) some data to a file system. It is to get the data written to the disk (it might stay in kernel filesystem buffers). Read sync(2) & fsync(2).
You cannot (in all cases) be sure that data is written to the disk (especially on power outage).
I would not bother and use syslog(3) (i.e. have my SIGTERM
handler set a volatile sigatomic_t
flag, and later test that flag elsewhere; on termination call syslog
...). Then document that your program is writing to the system log on termination, and leave the responsability of ensuring that the system log is written (to some disk somewhere, perhaps on the network) to the sysadmin.
The concrete behavior of shutdown is mostly a sysadmin issue. It really depends upon the actual system (including linux distribution and hardware) and the sysadmin's skills. Some file systems are remote or (for cheap USB keys) very slow file systems (and writing to them can be lost).
Imagine also a system with a buggy daemon (not yours but something else) which take ages to terminate. Then your daemon might not have time to do something sensible. So you have to trust the sysadmin.
I don't understand why you are asking your question. It depends upon how the entire system is administrated and set up. It really is different on million dollars servers and on a laptop.
来源:https://stackoverflow.com/questions/24900485/to-what-extent-can-one-rely-on-writing-to-disk-when-sigterm-is-given