Best way to gracefully exit a background process?
Hello,
I am using a program that reads in data from a serial port and then sends that data out over a TCP connection. The problem I'm having is that the only way I know to exit the program is to do a 'kill PID', but doing this means the program doesn't go through the motions of closing the TCP connection properly so I have to wait some random period of time for the port to free itself or else when I try to start it back up it tells me that it can't bind to the specified port. The general structure of the program is as follows Code:
int main(){ -robert |
kill works by "sending a signal" to the process in question. If the process does not "catch" the signal, the action of the default signal that is used is to kill the process gracefully. But, unless kill -9 is used, that signal can be caught or ignored.
You can use this signal-handling capability in your application to cause it to terminate its own loop gracefully, or to reload configuration files or whatever you need to do. However, having issued a signal, you will still need to wait some unpredictable amount of time for the process to die. One possibility is to write your code such that, if it cannot bind to the specified port, it waits for a random (short...) period of time and then tries again a few times, terminating with a "cannot bind" message only if it fails in all of its attempts. (A simple example of how signals can be used to good effect is the implementation of the Apache command, apachectl graceful.) |
All times are GMT -5. The time now is 11:29 PM. |