我正在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)
呢?或者有什么更好的解决办法吗?
您可以尝试使用
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;
}