Results 1 to 3 of 3
I'm trying to do some cleanup (write open files) when Linux shuts down. I thought the right method would be to trap SIGTERM and do the necessary processing. Here's my ...
- 02-04-2010 #1Just Joined!
- Join Date
- Feb 2010
- Posts
- 1
Application Cleanup on Shutdown
I'm trying to do some cleanup (write open files) when Linux shuts down. I thought the right method would be to trap SIGTERM and do the necessary processing. Here's my sample code:
When I run this, and press Ctrl-C, it write "got 2" to test.txt. However, if I logout/reboot, nothing is written to the file.Code:#include <stdio.h> // for File I/O #include <signal.h> // for signals #include <unistd.h> // for sleep() void handler(int signal) { FILE *out=fopen("test.txt","at"); if (out) { fprintf(out,"got %d\n",signal); fclose(out); } } int main() { signal(SIGTERM,handler); signal(SIGINT,handler); sleep(30); }
Any help or ideas would be appreciated!
-Ron
- 02-06-2010 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
What is your working directory when you create this file? If in /tmp then it will be (possibly) nuked on reboot. Anyway, what happens if you do the fopen() call in main and just print/flush in the handler? IE,
Code:#include <stdio.h> // for File I/O #include <signal.h> // for signals #include <unistd.h> // for sleep() FILE* out = 0; void handler(int signal) { if (out) { fprintf(out,"got %d\n",signal); fflush(out); } } int main() { out=fopen("test.txt","at"); signal(SIGTERM,handler); signal(SIGINT,handler); sleep(30); /* No need to close 'out' as it will be closed automatically. */ }Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!
- 02-06-2010 #3Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
In any case, if you aren't placing this file in /tmp, then perhaps the OS is not sync'ing the discs when you reboot. It should, but I don't know what's been done to your system configuration. One of the shutdown scripts might have been altered to change that behavior. So, if my example code doesn't work when you reboot, try executing a specific system sync command before you reboot. If that works, then you know your OS is not functioning properly at shutdown.
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!


Reply With Quote