Search code examples
c++stringmultithreadingstdexternal

How to use system() with std::thread together in C++


I am writing a C++ program on a win10 platform. I need to launch an external exe file in the second thread. The path of this external file is stored in a std::string object.

This external program will run for a very long time and it will output a result file every minute. And my main thread will go and read this file every minute. So I don't want the second thread to block my main thread.

I first write the following code, it can work:

string exePath = "external_program.exe";
const char* exePathChar = exePath.c_str();
system(exePathChar);

Then I update the code and try std::thread to enable a new thread to run the external exe file. But system() cannot open the specified file.

string exePath = "external_program.exe";
const char* exePathChar = exePath.c_str();
thread t1(system, exePathChar);
t1.detach();

I try to define the path as char* type at the beginning and the code works:

const char* exePathChar = "external_program.exe";
system(exePathChar);

The problem is that this file path is not fixed, it needs to read the external json file to get it, and the load function can only return string type. So how can I pass this string type path parameter to the thread t1(system)? Or is there any better solution?


Solution

  • You can try to use ShellExecute() instead of system():

    void RunExe(const std::wstring& exe)
    {
        ShellExecute(NULL, L"open", exe.c_str(), NULL, NULL, SW_SHOWDEFAULT);
    }
    
    int main(void)
    {
        std::jthread(RunExe, L"notepad.exe").join();
    
        std::string test = "Test text";
    
        std::cout << test << std::endl;
        return 0;
    }
    

    It's located in windows.h