I'm trying to launch a Python script by using the system call through C++, on Ubuntu. The problem is that this command sometimes works, but more often than not, it fails and throws one of two errors:
sh: 1: Syntax error: EOF in backquote substitution
sh: 1: xK-��: not found
The code I'm using:
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());
Any idea what's going on here?
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()); });