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", ???);

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

    fprintf(stderr, "Received signal: %d\n", s);

    /* additional signal-handling code follows */

(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.)

1 preferably to stderr, but either stdout or some file is also OK.

  • 2
    $\begingroup$ I wouldn't do this with Ctrl-C. If you just need to check memory usage periodically, you can set a scheduled task that will print it. A signal handler won't be able to call back to the Mathematica kernel because it is invoked at an unpredictable time when the kernel may not be in a state that would allow this to work, even theoretically. All it could do it set some flag that can be checked later from Mathematica code. If you say that you are running Mathematica code that takes long and can't check for a flag, just scheduled tasks which use a pre-emptive evaluation. $\endgroup$ – Szabolcs May 22 '16 at 16:22
  • $\begingroup$ @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. $\endgroup$ – kjo May 23 '16 at 10:59
  • $\begingroup$ @Szabolcs: I did not know about scheduled tasks. I will now go read up on them. Thanks for the pointer. $\endgroup$ – kjo May 23 '16 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.