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
On linux (and perhaps other OSes?) you can use a lock file idiom (but it's not supported with some file-systems and old kernels).
I would suggest to use Interprocess synchronisation objects.
E.g., using a Boost Interprocess named semaphore:
If you start one copy in the back ground, new copies will "refuse" to start ("Oops, second instance") for about 30s.
I have a feeling it might be easier to reverse the logic here. Mmm. Lemme try.
some time passes
Hehe. That was more tricky than I thought.
The thing is, you want to make sure that the lock doesn't remain when your application is interrupted or killed. In the interest of sharing the techniques for portably handling the signals:
There's a lot that could be explained there. Let me know if you're interested.
Here's a testrun on my system: