通过C++调用系统不一致失败

Calling the system through C++ inconsistently fails

我正在尝试通过 C++ 在 Ubuntu 上使用系统调用来启动 Python 脚本。问题是这个命令有时会起作用,但通常会失败并抛出以下两个错误之一:

sh: 1: Syntax error: EOF in backquote substitution
sh: 1: xK-��: not found

我使用的代码:

std::string pythonPath = "/home/myuser/Programs/miniconda3/envs/Py37/bin/python3.7";    
std::string viewerScript = "/home/myuser/Projects/Pycharm/MyProject/script.py";
std::string command = pythonPath + " " + viewerScript;
std::thread* t = new std::thread(system, command.c_str());

知道这里发生了什么吗?

c_str返回的数据缓冲区只保证在您下次以各种方式访问​​该字符串之前有效,特别是销毁它。因此,如果 command 即将超出范围,则这是破坏缓冲区的线程与使用 system 中的缓冲区的新线程之间的竞争。

与其创建一个以 system 作为入口点的线程,不如使用按值获取字符串的 lambda,使其保持活动状态直到 system 完成处理。

std::thread* t = new std::thread([command]() { system(command.c_str()); });