Home > other >  How to execute a function with parameters just before exiting a code in C ?
How to execute a function with parameters just before exiting a code in C ?

Time:08-25

I want to trigger a function with parameters just before exiting the program (exit by "return" in the main or by closing the console). My function will print the values of certain variables in a file.

Using the function "atexit" not help me because the pointer to the function is without parameters.

Thanks

P.S. My major problem is when I interrupt the execution of my program by closing the console, I want to get tthe value of some variables at that moment :

ostream out("myFile.txt");
int **S;
int n;
...
void fn(void)
{
  out << "S = " << endl;
  for(int i=0; i<n; i  )
  {
      for(int j=0; j<n; j  )
      {
          out << S[i][j] << " " << endl;
      }
      out << endl;
  }
}
...
int main()
{
   atexit(fn); // not working if i interrupt the execution
   ... // a big loop of code
   return 0;
}

I think it will be easy to understand mu issue with this example.

Regards

CodePudding user response:

Thanks to all of you, the answer proposed by @JeremyFriesner gives me the right thing to do, my code will be like :

#include <iosrteam>
#include <Windows.h>
...
int **S;
int n;
ofstream out("MyFile.txt");
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
    switch (CEvent)
    {
        case CTRL_C_EVENT:
        case CTRL_BREAK_EVENT:
        case CTRL_CLOSE_EVENT:
        case CTRL_LOGOFF_EVENT:
        case CTRL_SHUTDOWN_EVENT:
            out << "S = " << endl;
            for(int i=0; i<n; i  )
            {
                for(int j=0; j<n; j  )
                {
                    out << S[i][j] << " " << endl;
                }
                out << endl;
            }
    }
    return TRUE;
}
...
int main()
{
    if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE) == FALSE)
    {
        cout << "The handler is not going to work." << endl;
    }
    ... // a big loop of code
    return 0;
}

This will allow me to save my variables to my file just before closing the console. The unique inconvenient is the time we have to save my data is only 5 seconds if we interrupt the console by clicking the "x" and 30 seconds otherwise. I think the 5 seconds will be sufficient for the small data but otherwise, it will be lost.

Thanks a lot for everyone try to help me with this issue.

CodePudding user response:

One option that comes to mind is to use lambdas for this (https://en.cppreference.com/w/cpp/language/lambda) in conjunction with atexit. atexit takes a function pointer to a function with no arguments. What we can do here is wrap the function call we want to happen in a lambda. Let me explain what I mean.

First we have to make sure we're on the same page with lambdas. Basically, you can think of them as unnamed functions. An important thing to note is that with lambdas in C , we can capture variables in the current context, which we call our captures. This just means when the lambda is called, it will be able to reference these variables and the values they hold at the time of capture. With that in mind, consider this example:

int x = 1;
auto myLambda = [x](){ return x; };

We've "captured" the value of x by putting it inside of those square brackets. Now, when myLambda is run (which we do with the code myLambda()) the code in the curly braces is executed and we get the value of x. But what's neat is that this works outside the context x was defined.

With all this in mind, what I recommend you do is write a lambda which captures the variables you want to use as parameters in the function you want to call. Then, within the lambda, call your function, passing those values as the parameters. This essentially creates what we can call a "wrapper function" which has zero arguments but calls a function which has arguments. Now you can pass this lambda into noexit. That lambda might look something like:

auto yourLambda = [parameter1, parameter2](){ return someFunc(parameter1, parameter2); };

Naturally, replace the parameters with your variable names and someFunc with your function name.

Hope this helps!

  •  Tags:  
  • c
  • Related