Reputation: 857
Is there a platform independent way in C++11 (boost is available) to make sure that only one instance of an application is started at a time? (I'd prefer not to run with the "file and (f)lock" method as it requires platform specific code, but I will do so if there is no better way.)
There is no (simple) other way like an unavailable port that I can use as a criterion in my scenario neither. And yes, I am aware of DOS problems - so no need to point those out.
I found the following similar question suggesting a solution with boost. The solution has two problems though:
shared_memory_object::remove("shared_memory");
is missing (in the case "the race was won"). But I am not really familiar with boost::interprocess
, so maybe I am wrong?!I also found this question. No answer there that excites me. But it's a C++98 question so maybe with C++11 or boost there is a new/different way now?
Upvotes: 4
Views: 1909
Reputation: 5309
You can bind to a certain port, for example, using ASIO:
#include <iostream>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/io_service.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::ip::udp::socket sock(io);
sock.open(boost::asio::ip::udp::v4());
boost::system::error_code ec;
sock.bind({boost::asio::ip::udp::v4(), /*your port here*/}, ec);
if (ec)
std::cout << "Not mine\n";
else
std::cout << "It's mine\n";
return 0;
}
If it succeeds, then it's the first application, otherwise it's already running.
Upvotes: 1
Reputation: 136425
You can do file locking in platform independent way with boost.
Lock a file or its own executable.
Upvotes: 4