如何在 C++ 中将 system() 与 std::thread 一起使用

问题描述 投票:0回答:1

我正在win10平台上写一个

C++
程序。我需要在第二个线程中启动外部 exe 文件。该外部文件的路径存储在
std::string
对象中。

我先写了下面的代码,可以运行:

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

然后我更新代码并尝试

std::thread
启用新线程来运行外部exe文件。但是
system()
无法打开指定的文件。

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

我尝试在开头将路径定义为 char* 类型,并且代码有效:

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

问题是这个文件路径不固定,需要读取外部

json
文件才能获取,而load函数只能返回
string
类型。那么如何将这个
string
类型路径参数传递给
thread t1(system)
呢?或者有什么更好的解决办法吗?

c++ string multithreading std external
1个回答
0
投票

您可以尝试使用

ShellExecute()
代替
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.