# How to get a script to print MaxMemoryUsed[] upon getting a system signal?

I want to instrument a Mathematica script so that, upon receiving any system signal (e.g. SIGINT, aka Ctrl-C) it will print1 the value returned by MaxMemoryUsed[].

I have read this earlier answer and the LibraryLink docs, but I still can't figure out how to adapt the solution given in that answer so that my_handler can invoke MaxMemoryUsed, and print out its result. IOW, I can't figure out what to replace the ??? below with so that my_handler's printout shows the value returned by MaxMemoryUsed[]:

void my_handler (int s) {

fprintf(stderr, "MaxMemoryUsed[] returned: %d\n", ???);

/* ------------------------------------------------------- */


(One other possible way to achieve what I'm trying to do would be something like an atexit mechanism, but I have not been able to find anything like that for Mathematica. Yet a third possibility would be to implement the script so that it periodically prints the value of MaxMemoryUsed to a file. Unfortunately, for most of the script's lifetime, it is evaluating a single, irreducible Mathematica expression, and I don't know how to implement frequent periodic updating of an output file under these circumstances. In any case, even if I knew how to do it, this last alternative is a distant second-best.)
• @Szabolcs: Thanks for your comment. To be clear: I don't want to use a signal in order to find out the memory usage. Rather, I want to find out the memory being used at the time that the process receives a signal. I do not send the signal to the process. The signal is sent by the job-managing software (which I have no control over). Therefore, the timing of the call to MaxMemoryUsed is critical. – kjo May 23 '16 at 10:59