I have a console application which I am trying to make able to run just once at a time. I have used boost interprocess library shared_memory_object to do that. See the code snippet below,
boost::scoped_ptr<shared_memory_object> sharedMem;
try
{
sharedMem.reset(
new shared_memory_object(create_only, "shared_memory", read_write));
} catch(...)
{
// executable is already running
cerr << "Another instance of this program is running!" << endl;
return 1;
}
// do something
shared_memory_object::remove("shared_memory"); // remove the shared memory before exiting the application
The thing is that, the method prevents my application from running more than once at the same time; however, let's assume that the user stops the program running, then the memory will not be freed and next time when the user tries to run the program again, it will not run. Do you have any suggestions ?
P.S. C++ console application, OS: Ubuntu (but a solution which will work on the other platforms as well would be perfect ). Thank you
What you need to do is catch unexpected terminations of the program and free the shared memory object accordingly. You can catch
SIGINTas follows using thesignal.hPOSIX header:And you can catch program termination in the same manner using the
atexit()function. Documentation here.