I currently have a program I have written in C on a server that has an infinite loop that processes information, each loop takes about 5 minutes to complete. I would like to have the following functionality in a shell script:
- Terminate C program
- Make source
- Run program
The problem is, I don’t know how to tell my C program to exit without doing something like ctrl+c, I would rather it finished processing the information it is currently working on before terminating itself.
The POSIX standard way to tell a process to finish its business and exit cleanly is to send it a
SIGTERMsignal. Depending on your application it may or may not be appropriate to exit onSIGINT, which is meant to interrupt a process, not terminate it. (Control-c sendsSIGINT.)Try putting a flag in your tight loop; check the flag at a time when it is easy to exit, but still frequently enough to exit promptly. In your case, receipt of a
SIGTERMmight put a message on the system log right away, then promise to exit within the next 5 minutes.Your signal handler will look like this:
I check the global
staticvariablesignalledafter every I/O operation, which means many times per second.Here’s my code to catch and restore signals:
(This code is from a library, so I’m being extra careful to leave things the way I found them.)
Bonus trick: when time expires (this is a TV recording library), the timer just sets
signalled = SIGTERM, and the same logic is used to exit the recorder normally.