• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • Last Modified:

A function to execute at program termination?

I'm writing console applications on NT. My program runs in a while loop that it never exits, but I have to do some clean up procedures when the program is killed. I put all these procedures in a clean_up function and use atexit() to achieve this, but when I use Ctrl-C to terminate the program, my clean_up function is not executed. What is the best way to ensure the clean_up function is executed? (The program may be killed in ways other than Ctrl-C also.)
0
chanmo
Asked:
chanmo
  • 3
  • 3
1 Solution
 
chensuCommented:
Use the SetConsoleCtrlHandler function. The routine will be called for CTRL_C_EVENT, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT.
0
 
chanmoAuthor Commented:
Does SetConsoleCtrlHandler() work for NT service program? My program will be turned into NT service eventually. BTW, will this function works with window applications? Thank you.
0
 
chensuCommented:
>Does SetConsoleCtrlHandler() work for NT service program?

Yes, I think so.

>will this function works with window applications?

You mean GUI applications? No, you need to use the WM_KEYDOWN, WM_DESTROY,  WM_QUERYENDSESSION and WM_ENDSESSION messages.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
chanmoAuthor Commented:
SetConsoleCtrlHandler() works fine for console program, but not for NT services. The clean up function is not executed when I stopped the NT service in Control Panel.
0
 
chensuCommented:
For NT services, you should call the RegisterServiceCtrlHandler function in your ServiceMain function.
0
 
chanmoAuthor Commented:
Thank you very much for your help!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now