Search code examples
c++multithreadingstdthread

Run an app and forget in a portable way


I am writing a small updater utility that is being called from the main program. The main program terminates right after the call and lets the updater copy all the updated files and then it should re-launch the main program. However that last bit is starting to give me a headache.

I can run the program with std::system (I know, unsafe, but portable) just fine but then the updater just hangs there waiting for the main program to finish. I was searching for ways to make the call fire & forget and the threads seems like the best idea.

However this:

std::system("app");

hangs the updater as it waits for return from system. Whereas this:

std::thread(std::system, "app").detach();

nor variant

std::thread t(std::system, "app");
t.detach();

seem to do anything. But when I join the thread with:

std::thread t(std::system, "app");
t.join();

it does run the app but still waits for its return just like in the original code. Why can't the detached thread run the app?


Solution

  • Any thread, whether detached or not, will die if its process finishes(on most systems). Give some time before the updater end execution, and the thread may be able to actually make the call:

    #include <chrono>
    #include <cstdlib>
    #include <thread>
    
    void do_app() {
      std::system("app");
    }
    
    int main() {
      std::thread(do_app).detach();
      std::this_thread::sleep_for(std::chrono::seconds(2));
    }