Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

fork - How to inherit stdin and stdout in python by using os.execv()

First, I wrote a c++ code as follows:

#include <cstdio>
int main()
{
    int a,b;
    while(scanf("%d %d",&a,&b) == 2)
        printf("%d
",a+b);
    return 0;
}

I use g++ -o a a.cpp to complie it.

Afterwards, I wrote python code as follows:

import os,sys
sys.stdin = open("./data.in","r")
sys.stdout = open("./data.out","w")
pid = os.fork()
if pid == 0:
    cmd = ["./a","./a"]
    os.execv(cmd[0],cmd)

However, the data.out file contains nothing. That is to say, the child process did not inherit stdin and stdout from his parent process. But when I wrote a c++ code as follows:

#include<unistd.h>
#include<cstdio>
int main()
{
    freopen("data.in","r",stdin);a
    freopen("data.out","w",stdout);
    int pid = fork();
    if(pid == 0)
    {
        char* cmd[]= {"./a","./a"};
        execv(cmd[0],cmd);
    }
    return 0;
}

I got the right answer in the data.out, that is to say execv works in the c++ code.

So, what I should do to let execv also works in python? I really need this function to work, could anybody can tell me? thanks a lot!

data.in contains the following:

1 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your python code, you've opened new IO streams and set the sys.stdin and sys.stdout Python names to point to these. They will have their own file descriptors (most likely 3, and 4). However the standard file descriptors, 0, and 1 will remain unchanged, and continue to point at their original locations. These are the descriptors inherited when you exec into stdin and stdout in your C++ program.

You need to make sure that the actual file descriptors are adjusted before execing.

os.dup2(sys.stdin.fileno(), 0)
os.dup2(sys.stdout.fileno(), 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...