Click here to Skip to main content
15,672,517 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a console-based application, it may be run as a windows service or as a console application, but it also may be spawned by another application using CreateProcess with hidden console Window.
If I want to terminate cleanly the application, I can stop the service (when running as service), I can type CTRL+C in the console window and trap the SIGINT signal (when as a console), I can also install a ControlHandler and trap the console close (when as a console), but when spawning it with CreateProcess, I cannot find a reliable way to terminate it cleanly.
From the documents I read, the ::TerminateProcess API sends a WM_CLOSE , that is obviously ignored by a console application, and there are people out there suggesting to install an event pump inside the console application to handle WM_CLOSE.
Also, iv heard of using FindWindow & then post a WM_CLOSE.

Please suggest...


There are many ways to do this. You could use the GenerateConsoleCtrlEvent function[^] to send a signal to the console application. If you implement a control handler.. you could catch the signal and properly terminate.

All of the other methods such as thread messages are nothing more than a hack[^].

Best Wishes,
-Ugly Hack
Share this answer
From (Terminating a Process[^]) "The exit code for a process is either the value specified in the call to ExitProcess or TerminateProcess...". Of course, the preferred way is to use ExitProcess() function.
But to simply terminate a certain process created by CreateProces() API you can use its last parameter LPPROCESS_INFORMATION lpProcessInformation (CreateProcess function[^]) to get a handle to the created process. Then, call TerminateProcess()(TerminateProcess function[^])
Share this answer
call TerminateProcess(handleFromCreateProcess,&exitcode)
make sure to wait because TerminateProcess returns immediately after initiating termination. you need to call WaitForSingleObject function to make sure process is terminated.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900