Function execution on exit

Hi
I want to create a function, which is called whenever the program is being closed (f.e. through Ctrl+C). I'm thinking of somethin similar to a "global" drop implementation, which then will send a short message to a server.

Thanks for any help,
Trembel

There is libc::atexit which you might could use.

See https://crates.io/crates/ctrlc for Ctrl+C handling.

1 Like

Be aware that when it comes to async function calls (e.g. the ctrl+c call from the OS), there are certain things which are not allowed, e.g. using a mutex, printing to stdout etc, because it could be, that the program has been stopped while holding the corresponding mutex. The example on the doc page is pretty good and only modified a AtomicBool, which is allowed, because no mutex is involved in this case.

Thanks for your answers.
However, on exit I have to remove a file in the file system which I therefore think will not be possible using atexit. Would it be a possibility to create a dummy stuct including a drop implementation which executes the stuff I need?

Static variables will not ever be dropped, as not all platforms support such behavior. You can call your dtor at signal handler though, but it still is signal handler.

The most correct way you might want to do this:

  • Use of RAII in main() ‒ the destructor runs before you exit your main.
  • Use the ctrlc (or signal-hook or something) to flag your application to please shut down.

This will not remove the file on any crash, SIGKILL, direct call to exit, etc, but well, for most of these, it never will.

What file do you need deleted? If you look at the tempfile crate, it has the ability of files cleaned by the OS.

2 Likes

I'm into high-performance computing, mostly in form of simulations. The high amount of data (~1TB is reached quickly) should then be transfered from a cluster to a storage-server. At least, under all circumstances, if a simulation gets terminated, the files should be deleted to free resources for computations of others.
I think I'm gonna try the approach of taking tmpfile and destructing before exiting main (in this form, if the process gets killed, at least the OS will take care of the data after some time).