DrP3pp3r
DrP3pp3r

Reputation: 857

one instance of application, platform independent, C++11

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:

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

Answers (2)

Jamboree
Jamboree

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

Related Questions