問題描述
通過 C++ 調用系統不一致失敗 (Calling the system through C++ inconsistently fails)
我正在嘗試在 Ubuntu 上通過 C++ 使用系統調用來啟動 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());
知道是什麼在這裡進行嗎?
參考解法
方法 1:
The data buffer returned by c_str
is only guaranteed to be valid until the next time you access the string in various ways, in particular destroying it. So if command
is about to go out of scope, it's a race between this thread destroying the buffer, and the new thread using the buffer in system
.
Rather than making a thread with system
as an entry point, use a lambda which takes the string by value, keeping it alive until system
is done with it.
std::thread* t = new std::thread([command]() { system(command.c_str()); });