【问题标题】:Calling the system through C++ inconsistently fails通过 C++ 调用系统不一致失败
【发布时间】:2021-08-09 15:20:20
【问题描述】:

我正在尝试在 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());

知道这里发生了什么吗?

【问题讨论】:

    标签: python c++ bash ubuntu system


    【解决方案1】:

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

    不要使用system 作为入口点创建线程,而是使用按值获取字符串的lambda,使其保持活动状态直到system 完成。

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

    【讨论】:

    • 感谢您的回答 Sneftel,我实际上正要发布我找到的解决方案,但我没有很好地解释它为什么起作用。我已将字符串与系统命令一起移动到一个函数中,然后在线程中启动该函数。它与您的解决方案基本相同!
    • new std::thread 也有点可疑。 std::thread 已经是句柄类; std::thread t{ [command]... 也同样有效。
    猜你喜欢
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多