1

I want to read the exit value from my console application to exit all the related threads with that application before exit.

enter image description here

abdo.eng 2006210
  • 507
  • 2
  • 6
  • 12

3 Answers3

1

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".

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

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
}
GeniusIDS
  • 91
  • 3
  • @GeniusIDS lol did you just copy paste the post that i linked to? – Karthik T Jan 13 '13 at 13:02
  • @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
0

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.

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40