简体   繁体   中英

Using fork() and exec() to execute Python code from C++

I am trying to use exec() to run Python from C++, and use pipes to communicate between the processes. I found that the C++ process keep waiting at the exec() command after the Python process terminates, which makes it unable to execute the codes below that line.

Please check my code below (I have minimized the problem so the acutal communication part is removed)

C++ file:

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;
}

Python file:

import os  
import time
import struct
    
if __name__ == "__main__":
    print("in python")
    exit()

Output:

ece:~/cpp> ./Pipetest
parent started
parent terminated
child started
child before exec
ece:~/cpp> in python
(blinking cursor here)

For the C++ file, if I remove the fork command and simply call exec() in the main function to execute the Python program, it will behave as expected and terminate successfully. Could anyone tell me what is going on?

Update: Thanks for all the answers! Now I see that codes after exec() will not be executed. However, the output still confuses me because the new command prompt does not show up (in my case, it's ece:~/cpp>). In fact, it shows up only after I enter something. This happens even when I replace exec() with system(). Why is this happening?

You aren't wait ing on the child process, so the parent exits during (or, as in your example output, before) the (relatively long) startup time for Python and the shell prints its next prompt before the child prints anything. You can see this in that if you type anything on the “(blinking cursor here)” line, it gets executed as the next shell command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM