It depends of how your service is stopped. Only you knows: the service start and stop methods are things that you should document for users of your service, and ideally provide.
If your service is stopped by sending a signal to it by calling kill
from a shell script, this is asynchronous. The kill
command or system call sends a signal to a process and returns immediately. There is no mechanism for the process to call back to notify that it has processed the signal to its satisfaction. So you need to find another method to signal that you are done.
Many methods are possible, such as having the service create or remove a file and the control script watch for changes to that file. However they tend to be awkward. Sending a signal from an unrelated process is not a very good method if you need feedback when the service is finished.
If your service is stopped via a stop
directive in an Upstart service description, Upstart sends a signal to the process. Upstarts then waits for a few seconds for the process to stop. Because Upstart is the parent of the process, it receives a notification from the kernel (a SIGCLD signal) when the process exits. This only works well when the process doesn't fork to put itself in the background; Upstart service descriptions normally call daemons with an option telling them not to fork (e.g. ssh -D
).
Advanced services have a throttling command. When you call the throttling command, they stop accepting new connections. When all pending connections are closed, the service sends a positive reply to the throttling command and then exits. The communication method is typically a Unix or IP socket.
halt
,poweroff
, or similar. – msw Sep 04 '13 at 09:23