How do you run a function on exit in C++ - c++

I have a function that I want to run whenever my program exits:
void foo() {
std::cout<< "Exiting" << std::endl;
}
How do I register it to be run whenever the program exists, regardless of when and why it exits - due to signal, exit() call, etc?

You can use the aptly named std::atexit function in the cstdlib header:
#include <cstdlib>
void exiting() {
std::cout << "Exiting";
}
int main() {
std::atexit(exiting);
}
The system will maintain a stack of functions registered with atexit and call them each in the reverse order of their registration when either the exit function is called, or the program returns from main. You can register at least 32 functions this way.

I am answering as a Linux user, but all of this should apply to windows.
I had this similar question, so hopefully I can sum up previous answers and add my two cents.
Signals and abort(): ^C and ^Z can be "intercepted" to call your function before exiting, presumably with exit(). Signals SIGQUIT AKA ^\ and SIGKILL which has no key stroke cannot be intercepted. Here's an example for using the csignal header and a C++ lambda.
#include <iostream>
#include <csignal>
#include <cstdlib>
using namespace std;
int main()
{
//signal requires lam take an int parameter
//this parameter is equal to the signals value
auto lam =
[] (int i) { cout << "aborting" << endl; exit(0); };
//^C
signal(SIGINT, lam);
//abort()
signal(SIGABRT, lam);
//sent by "kill" command
signal(SIGTERM, lam);
//^Z
signal(SIGTSTP, lam);
while(1)
{
}
return 0;
}
Exit: Since I used exit() in my examples above, care must be taken here. If the function being run is a clean-up function that only needs to run once, perhaps a static variable has_run could be used. Or in the example above, raise() a signal that you can't intercept. But those tend to come with core dumps which just feels dirty. Your choice, here. An example follows
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
//called with no parameters
auto lam = [] () { cout << "at exit"; };
atexit(lam);
return 0;
}
Take note that c++11 added a quick_exit which has an accompanying at_quick_exit which act the same as above. But with quick_exit no clean up tasks are performed. In contrast, with exit object destructors are called and C streams are closed, with only automatic storage variables not getting cleaned up.

You could put it in the destructor of a class with a global instance.
class SomeGlobalStuff {
~SomeGlobalStuff() {
foo();
}
static SomeGlobalStuff instance;
};
// putting this in a single compilation unit.
SomeGlobalStuff SomeGlobalStuff::instance instance;
But like any other method, you have to remember that you cannot use any data if you cannot garantee that it still exists. Deallocation of global objects is done in a arbitrary order, so basically, you cannot use std::cout in the foo() function. atexit() is worse in this regard, because whether it executes before or after destruction of global objects depends on the compiler and compiler options.
And anyway, you still have to handle signals correctly. You have to choose which signals to handle and which to not handle (you most likely don't want to handle SIGSEGV). You cannot escape signal handling. And remember that signals may interrupt your program at any time (unless masked) so your data structures might be in a arbitrary state, in the middle of an update.

The only way (in Unix and Unix-like operating systems) to regain control after a process exits is to wait(2) for it. Short of a powerfail, kernel panic, or forced reboot, this should work:
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
int AtExit() {
pid_t pid = fork();
if(pid < 0) return pid;
if(pid == 0) return pid;
pid = waitpid(pid, 0, 0);
return pid;
}
int main () {
if(AtExit()) {
std::cout << "Exiting\n";
return 0;
}
std::cout << 7 << "\n";
}

Related

Is it possible to test that an abort-routine doesn't return?

I have to test a library that provides its own abort_routine() function (that calls abort() internally, but the implementation may change).
One of the requirements for this abort_routine() is that it may not return.
I'm wondering if it's possible to test this requirement?
UPDATE:
I'm not using gtest, only llvm's lit and stuff like these: return 0, return 1, assert(false).
This is a nice use case for fork and I use it myself in my tests.
You can simply fork(), run the function in the child, _exit() the child, reap the result, and if it indicates the process was signaled with SIGABRT, the child aborted, otherwise it didn't.
Example code:
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
int fork_and_reap(int *Ws, void Fn(void *), void *Arg)
{
pid_t pid; if (0>(pid=fork())) return -1;
if(0==pid) (void)Fn(Arg), _exit(0);
else for(;;){
if(0>waitpid(pid,Ws,WUNTRACED)){
if(EINTR==errno) continue;
else abort();
}else if(!WIFEXITED(*Ws)&&!WIFSIGNALED(*Ws)){ //shouldn't have stopped
if(0>kill(pid,SIGTERM) ||0>kill(pid,SIGCONT)) abort();
}else break;
}
return 0;
}
void aborting(void *A){ (void)A; abort(); }
void not_aborting(void *A){ (void)A; }
int main()
{
int ws;
if(0<=fork_and_reap(&ws, aborting, 0) && WIFSIGNALED(ws) && WTERMSIG(SIGABRT)) puts("aborted"); else puts("didn't abort");
if(0<=fork_and_reap(&ws, not_aborting, 0) && WIFSIGNALED(ws) && WTERMSIG(SIGABRT)) puts("aborted"); else puts("didn't abort");
}
As a general solution, you could test it by running it as a separate process, something like:
int main()
{
abort_routine();
printf("Didn't abort\n");
return 0;
}
You will be able to see when you run it as a child process if it aborted (printed some abort output instead, non zero exit) or not (printed that output and exited with zero).
This is roughly how the "death tests" in gtest work, https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#how-it-works
Under the hood, ASSERT_EXIT() spawns a new process and executes the death test statement in that process. The details of how precisely that happens depend on the platform
See the _Noreturn keyword:
"The _Noreturn keyword appears in a function declaration and specifies that the function does not return by executing the return statement or by reaching the end of the function body (it may return by executing longjmp). If the function declared _Noreturn returns, the behavior is undefined. A compiler diagnostic is recommended if this can be detected."
If a function is declared as such, the compiler should give a diagnostics message. So you do not need to test it but can inspect the compiler messages and do a code review
https://en.cppreference.com/w/c/language/_Noreturn

How to call a function on a thread's creation and exit?

#include <pthread.h>
#include <iostream>
using namespace std;
void OnCreateThread()
{
cout << "Create a thread." << endl;
}
void OnExitThread()
{
cout << "Exit a thread." << endl;
}
void f(void*) {}
int main()
{
//
// What to do here ???
//
pthread_t dummy;
pthread_create(&dummy, 0, f, 0);
pthread_create(&dummy, 0, f, 0);
while (true);
}
The code creates two native threads, other than std::thread, and I want it to output as follows:
Create a thread.
Create a thread.
Exit a thread.
Exit a thread.
It can be done under Windows by using FlsXXX functions.
However, I don't know whether it can also be done under Linux.
Is there a standard way under Linux?
How to call a function on a thread's creation and exit?
Pthreads API does not provide callbacks for thread creation (nor does std::thread API).
Solution is pretty simple however: Call the functions at the beginning and end of start_routine callback.
void* f(void*) {
OnCreateThread();
OnExitThread();
return nullptr;
}
In case you might want OnExitThread to be called even when the thread has been terminated prematurely, you might want to use pthread_cleanup_push to register it as a callback.
PS. The start_routine callback must return void*.
There exists at least a pthread_cleanup_push function that lets you add a function that will be called just after thread termination. Never heard about the same for creation, but some API may have such.

How to "interrupt" a function call?

I am doing a kind of shell: depending of the user's entry, I must call some function. I cannot modify the content of those called functions since my program is only a client and has no visibility of them.
But I want the possibility for the user to kill the call using CTRL+C. Here is the minimal code:
#include <csignal>
#include <iostream>
#include <unistd.h>
void do_thing(void)
{
std::cout << "entering in do_thing()\n";
while(42)
::sleep(1);
}
extern "C" {
void signal_handler(int);
}
class Shell
{
friend void signal_handler(int);
public:
static Shell & Instance(void)
{
static Shell instance;
return instance;
}
int run(void)
{
std::string buff;
while ((std::cin >> buff))
{
if (buff == "foo")
do_thing(); // this must be terminable
else
std::cout << "(nothing)\n";
}
return 0;
}
private:
Shell(void)
{
::signal(SIGINT, signal_handler);
}
void signal(int sig)
{
if (sig == SIGINT)
;// must terminal the function call
}
};
extern "C" {
void signal_handler(int sig)
{
Shell::Instance().signal(sig);
}
}
int main(void)
{
return Shell::Instance().run();
}
I considered three possibilities:
I tried to create a thread class derived from std::thread, with a kill() method that throws an exception. The function call is in a try-catch block. It works, but this is a bad solution since the destructor cannot be called, and the resource is never freed.
I considered using fork, but I think it is an overkill to just get the possibility of interrupt a function call.
I tried to throw an exception from the signal handler, but I saw that this is a bad idea since this is very compiler/OS dependent code.
How could you do the thing? What is the better solution?
Note: I deleted the old post because it was close requested, and took into consideration the C/C++ tags.
Essentially, no, there is no standard why to interrupt a thread in C++. Threads run co-operatively and as such, they need to "give up" control.
If the code for do_thing were modifiable, then you can create a flag (atomic) to signal that the thread should give up and exit. This can be periodically checked by the thread and complete as required.
Given the code for do_thing is not modifiable, there is a small window of opportunity that can be used to "kill" or "cancel" the thread (albeit it won't be "standard" and support will be limited to targeted platforms).
std::thread offers a function to retrieve a native_handle() that is implementation defined. Once obtained (and converted), it can be used to kill or cancel the thread.
If pthreads are being used, see pthread_kill (or pthread_cancel if supported by the target thread).
On windows, see the TerminateThread function.
Be warned; aside from the platform specific code required, the thread terminations generally leave the objects on that thread in "limbo" and with them, the resources they control.

How can I handle interrupt signal and call destructor in c++? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is destructor called if SIGINT or SIGSTP issued?
My code like this:
#include <iostream>
#include <signal.h>
#include <cstdlib>
void handler(int) {
std::cout << "will exit..." << std::endl;
exit(0);
}
class A {
public:
A() {std::cout << "constructor" << std::endl;}
~A() {std::cout << "destructor" << std::endl;}
};
int main(void) {
signal(SIGINT, &handler);
A a;
for (;;);
return 0;
}
When I pressed Ctrl-C, it printed:
constructor
^Cwill exit...
There is no "destructor" printed.
So, how can I exit cleanly?
With difficulty. Already, the code you've written has undefined
behavior; you're not allowed to output to a stream in a signal handler;
for that matter, you're not allowed to call exit either. (I'm basing
my assertions here on the Posix standard. In pure C++, all you're
allowed to do is assign to a variable of sig_atomic_t type.)
In a simple case like your code, you could do something like:
sig_atomic_t stopFlag = 0;
void
handler( int )
{
stopFlag = 1;
}
int
main()
{
signal( SIGINT, &handler );
A a;
while ( stopFlag == 0 ) {
}
std::cout << "will exit..." << std::endl;
return 0;
}
Depending on the application, you may be able to do something like this,
checking the stopFlag at appropriate places. But generally, if you
try this, there will be race conditions: you check stopFlag before
starting an interuptable system call, then do the call; the signal
arrives between the check and the call, you do the call, and it isn't
interrupted. (I've used this technique, but in an application where the
only interruptable system call was a socket read with a very short
timeout.)
Typically, at least under Posix, you'll end up having to create a signal
handling thread; this can then be used to cleanly shut down all of the
other threads. Basically, you start by setting the signal mask to block
all signals, then in the signal handling thread, once started, set it to
accept the signals you're interested in and call sigwait(). This
implies, however, that you do all of the usual actions necessary for a
clean shutdown of the threads: the signal handling thread has to know
about all other threads, call pthread_cancel on them, etc., and you're
compiler has to generate the correct code to handle pthread_cancel, or
you need to develop some other means of ensuring that all threads are
correctly notified. (One would hope, today, that all compilers handle
pthread_cancel correctly. But one never knows; doing so has
significant runtime cost, and is not usually needed.)
You need to exit from the main function's scope to have the destructor working:
#include <iostream>
#include <signal.h>
#include <cstdlib>
bool stop = false;
void handler(int) {
std::cout << "will exit..." << std::endl;
stop = true;
}
class A {
public:
A() {std::cout << "constructor" << std::endl;}
~A() {std::cout << "destructor" << std::endl;}
};
int main(void) {
A a;
signal(SIGINT, &handler);
for (;!stop;);
return 0;
}
It's because the context of the normal code and the signal handler is different. If you put the variable a in global scope (i.e. outside of any function) you will see that the destructor is called properly.
If you want to handle cleaning up yourself (instead of letting the run-time and OS handle it), you can have a conditional loop, something like this:
bool keep_running = true;
void handler(int) {
std::cout << "will exit..." << std::endl;
keep_running = false;
}
int main(void) {
signal(SIGINT, &handler);
A a;
while (keep_running);
return 0;
}
Memory should be freed anyway. but if you've got code to be handled, I guess you'd have to track all your objects and then destroy them as needed (e.g. having the constructor adding them to a std::set, while the destructor removes them again). However this wouldn't ensure proper order of destruction (which might require some more complex solution).
You could as well use your signal handler to set some flag that will leave the infinite loop (or whatever you're doing in your main loop) instead of simply terminating using exit().
exit terminates the process almost immediately; in particular, objects with automatic storage duration are not destroyed. Streams are also flushed and closed, but you're not allowed to touch streams from inside a signal handler. So...
Simply don't call exit from a signal handler; set some atomic flag to instruct the loop to end instead.
#include <iostream>
#include <signal.h>
#include <cstdlib>
sig_atomic_t exitRequested = 0;
void handler(int) {
std::cout << "will exit..." << std::endl;
exitRequested = 1;
}
struct A {
A() { std::cout << "constructor" << std::endl; }
~A() { std::cout << "destructor" << std::endl; }
};
int main() {
signal(SIGINT, &handler);
A a;
for (; !exitRequested; );
}

Simple example of threading in C++

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Can someone post a simple example of starting two (Object Oriented) threads in C++.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
Create a function that you want the thread to execute, for example:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
Now create the thread object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(You need to #include <thread> to access the std::thread class.)
The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)
The Code
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
More information about std::thread here
On GCC, compile with -std=c++0x -pthread.
This should work for any operating-system, granted your compiler supports this (C++11) feature.
Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in C++0x, which was just nailed down and hasn't yet been implemented.
The problem is somewhat systemic. Technically the existing C++ memory model isn't strict enough to allow for well-defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the C++0x standard on the topic.
Threads Cannot be Implemented as a Library
That said, there are several cross-platform thread C++ libraries that work just fine in practice. The Intel thread building blocks contains a tbb::thread object that closely approximates the C++0x standard and Boost has a boost::thread library that does the same.
oneAPI Threading Building Blocks
Chapter 19. Thread (Boost documentation)
Using boost::thread, you'd get something like:
#include <boost/thread.hpp>
void task1() {
// do stuff
}
void task2() {
// do stuff
}
int main (int argc, char ** argv) {
using namespace boost;
thread thread_1 = thread(task1);
thread thread_2 = thread(task2);
// do other stuff
thread_2.join();
thread_1.join();
return 0;
}
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
There is also a POSIX library for POSIX operating systems.
Check for compatibility:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
void *task(void *argument){
char* msg;
msg = (char*)argument;
std::cout << msg << std::endl;
}
int main(){
pthread_t thread1, thread2;
int i1, i2;
i1 = pthread_create(&thread1, NULL, task, (void*) "thread 1");
i2 = pthread_create(&thread2, NULL, task, (void*) "thread 2");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Compile with -lpthread.
POSIX Threads
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:
Class.h
class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};
Class.cpp
#include "DataManager.h"
void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}
bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}
Note that this example doesn't get into mutex or locking.
Unless one wants a separate function in the global namespace, we can use lambda functions for creating threads.
One of the major advantage of creating a thread using lambda is that we don't need to pass local parameters as an argument list. We can use the capture list for the same and the closure property of lambda will take care of the lifecycle.
Here is sample code:
int main() {
int localVariable = 100;
thread th { [=]() {
cout << "The value of local variable => " << localVariable << endl;
}};
th.join();
return 0;
}
By far, I've found C++ lambdas to be the best way of creating threads especially for simpler thread functions.
It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:
class RThread : public wxThread {
public:
RThread()
: wxThread(wxTHREAD_JOINABLE){
}
private:
RThread(const RThread &copy);
public:
void *Entry(void){
//Do...
return 0;
}
};
wxThread *CreateThread() {
//Create thread
wxThread *_hThread = new RThread();
//Start thread
_hThread->Create();
_hThread->Run();
return _hThread;
}
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it.
More information is in the wxThread documentation.