LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Best way to gracefully exit a background process? (https://www.linuxquestions.org/questions/programming-9/best-way-to-gracefully-exit-a-background-process-884981/)

robertH 06-07-2011 08:19 AM

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(){
  // initialize some stuff
  // open sockets and serial ports
  while(1){
    // read from serial send to TCP
  }
  // close sockets and serial ports
}

I just need a way to trigger a 'break' in the while loop rather than killing the process. I have to run the program in background because I am running multiple instances of it for multiple serial ports/sockets. Any thoughts? thanks for your help,
-robert

sundialsvcs 06-07-2011 08:32 AM

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.