CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2010
    Posts
    1

    Application Cleanup during Linux 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:

    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);
    }
    When I run this, and press Ctrl-C, it writes "got 2" to test.txt. However, if I logout/reboot, nothing is written to the file.

    Any help or ideas would be appreciated!

    -Ron

  2. #2
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Application Cleanup during Linux Shutdown

    Are you sure the 30s are enough? Maybe the application already exited before it received the SIGTERM?

    So I would suggest, trying with in infinite loop and sending the process SIGTERM from another window (kill -15 pid).
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  3. #3
    Join Date
    Nov 2003
    Posts
    1,902

    Re: Application Cleanup during Linux Shutdown

    Those functions (fopen, fprintf, fclose) technically aren't async-signal-safe.
    http://www.opengroup.org/onlinepubs/...l#tag_02_04_04

    Also, sleep() returns when a signal is delivered. To ensure 30 seconds go by:
    Code:
    unsigned seconds = 30;
    while (seconds > 0)
       seconds = sleep(seconds);
    gg

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured