[英]How to automatically execute chunks of C++ code (ideally from python)
[英]Using fork() and exec() to execute Python code from C++
我正在嘗試使用 exec() 從 C++ 運行 Python,並使用管道在進程之間進行通信。 我發現 Python 進程終止后,C++ 進程一直在等待 exec() 命令,這使得它無法執行該行下面的代碼。
請檢查我下面的代碼(我已將問題最小化,因此刪除了實際通信部分)
C++文件:
int main()
{
int pipe_cpp_to_py[2];
int pipe_py_to_cpp[2];
if (pipe(pipe_cpp_to_py) || pipe(pipe_py_to_cpp))
{
std::cout << "Couldn't open pipes" << std::endl;
exit(1);
}
pid_t pid = fork();
if (pid == 0)
{
std::cout<<"child started"<<std::endl;
char *intrepreter="python3";
char *pythonPath="./Pipetest.py";
char *pythonArgs[]={intrepreter,pythonPath,NULL};
std::cout<<"child before exec"<<std::endl;
execvp(intrepreter,pythonArgs);
std::cout<<"child after exec"<<std::endl;
close(pipe_py_to_cpp[0]);
close(pipe_cpp_to_py[1]);
close(pipe_py_to_cpp[1]);
close(pipe_cpp_to_py[0]);
std::cout<<"child terminated"<<std::endl;
}
else if (pid < 0)
{
std::cout << "Fork failed." << std::endl;
exit(1);
}
else
{
std::cout<<"parent started"<<std::endl;
std::cout<<"parent terminated"<<std::endl;
exit(0);
}
std::cout<<"cpp terminated"<<std::endl;
return 0;
}
蟒文件:
import os
import time
import struct
if __name__ == "__main__":
print("in python")
exit()
輸出:
ece:~/cpp> ./Pipetest
parent started
parent terminated
child started
child before exec
ece:~/cpp> in python
(blinking cursor here)
對於 C++ 文件,如果我刪除 fork 命令並在 main 函數中簡單地調用 exec() 來執行 Python 程序,它將按預期運行並成功終止。 誰能告訴我這是怎么回事?
更新:感謝所有的答案! 現在我看到 exec() 之后的代碼不會被執行。 但是,輸出仍然讓我感到困惑,因為沒有顯示新的命令提示符(在我的情況下,它是 ece:~/cpp>)。 事實上,它只有在我輸入內容后才會出現。 即使我用 system() 替換 exec() 也會發生這種情況。 為什么會這樣?
您不是在wait
子進程,因此父進程在 Python 的(相對較長的)啟動時間期間(或者,在您的示例輸出中,之前)退出,並且 shell 在子進程打印任何內容之前打印其下一個提示。 你可以看到這一點,如果你輸入的任何東西“(這里閃爍光標)”線,它就會為下一個shell命令執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.