I want to read the exit value from my console application to exit all the related threads with that application before exit.
-
Well you could always write to a logfile. – Daniel Figueroa Jan 13 '13 at 11:15
-
This is an OS question, not a C or C++ question. Can you label the question with whatever OS you're using? – Paul Hankin Jan 13 '13 at 11:19
-
1You can review this article [How to handle a ctrl break signal][1] [1]: http://stackoverflow.com/questions/181413/how-to-handle-a-ctrl-break-signal-in-a-command-line-interface – GeniusIDS Jan 13 '13 at 11:37
3 Answers
Take a look at https://stackoverflow.com/questions/298498/c-console-breaking. The standard library you need to use is csignal
What you can do is register for signals which force your app to close (SIGTERM) and perform logic there, like exiting your multiple threads. This post suggests that this should work with windows as well.
You could also register a function with atexit which seems to catch normal exit from main() etc, not sure if closing the terminal will count as "normal exit".
-
i want to catch the exit signal so i can closed all related programs before exit. – abdo.eng 2006210 Jan 13 '13 at 11:26
-
1@abdo.eng2006210 yes, and adding a signal handler for SIGTERM will do exactly that. – Karthik T Jan 13 '13 at 11:27
This work for me on Windows try it
#include <csignal>
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
namespace
{
volatile sig_atomic_t exit;
void signal_handler(int sig)
{
signal(sig, signal_handler);
exit= 1;
}
}
int main()
{
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
#ifdef SIGBREAK
signal(SIGBREAK, signal_handler);
#endif
while (!exit)
{
/* do something */
}
// Catch signal here
}

- 91
- 3
-
-
@KarthikT lol no i just explain in codes the code from previous link i posted [link] (http://stackoverflow.com/questions/181413/how-to-handle-a-ctrl-break-signal-in-a-command-line-interface) – GeniusIDS Jan 13 '13 at 21:48
Edit: Ok so it seems you want to be notified as soon as the process exits. Sorry, I misread your question due to the term "exit value". Well if you start the process via CreateProcess()
API, you should be able to do WaitForSingleObject()
on the handle. This function will block until the process exited. So you can place all the code which you want to be executed after the process stopped after this call, and all should be fine.
If you in fact want the exit code of a process (return X
in main()
):
Programmatically, you can use GetExitCodeProcess()
from WinAPI:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx
In the shell, use the %errorlevel%
variable.

- 4,438
- 1
- 20
- 40