通過 C++ 調用系統不一致失敗 (Calling the system through C++ inconsistently fails)


問題描述

通過 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()); });

(by TheTomerSneftel)

參考文件

  1. Calling the system through C++ inconsistently fails (CC BY‑SA 2.5/3.0/4.0)

#system #Python #C++ #ubuntu #bash






相關問題

asp.net c# sistem login (asp.net c# login system)

系統函數的彙編代碼(iPhone) (Assembly code to system functions (iPhone))

如何跟踪系統依賴關係? (How to track System Dependencies?)

使用 system() 甚至 passthru() 從 php 運行 python 腳本不會產生任何輸出。為什麼? (Running a python script from php with system( ) or even passthru( ) produces no output. Why?)

求解線性方程 (Solving a linear equation)

C++ 中的 System() 調用及其在編程中的作用 (System() calls in C++ and their roles in programming)

找不到傳遞給使用 Perl“系統”命令調用的程序的參數 (Cannot find argument passed to program called using Perl "system" command)

如何顯示所有用戶表中的所有列/字段? (How to display all columns/fields in all user tables?)

系統文件夾中的庫未加載正確的語言 (Libraries from system folder does not load correct language)

為什麼系統不返回主值? (Why system doesn't return main's value?)

通知未顯示,因為服務或警報管理器已被終止 (Notification not showing because service or alarm manager is killed off)

通過 C++ 調用系統不一致失敗 (Calling the system through C++ inconsistently fails)







留言討論