One platform-independent application instance, C ++ 11

Is there a platform-independent way in C ++ 11 (there is boost support) to make sure that only one application instance is launched at a time? (I would prefer not to start with the file and (f) lock method, as this requires platform-specific code, but I will do it if there is no better way.)

There is no (simple) other way than an inaccessible port, which I cannot use as a criterion in my scenario. And yes, I know about DOS issues, so you don’t need to specify them.

I found the following similar question offering a solution with a boost. The solution has two problems:

  • Minor: it seems that the challenge is shared_memory_object::remove("shared_memory");absent (in the case of "race was won"). But I'm not very familiar with it boost::interprocess, so maybe I'm wrong ?!
  • Major: If the program crashes, shared memory still exists, and therefore the next instance of the program will not start.

I also found this question. There is no answer that excites me. But this is a C ++ 98 question, so maybe with C ++ 11 or boost there is a new / different way now?

+4
source share
2 answers

, , 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 mine\n";
    return 0;
}

, , .

0

All Articles