![](/img/trans.png)
[英]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.