【问题标题】:How to inherit stdin and stdout in python by using os.execv()python中如何使用os.execv()继承stdin和stdout
【发布时间】:2012-01-19 23:10:48
【问题描述】:

首先我写了一段c++代码如下:

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

我使用g++ -o a a.cpp 来编译它。

后来我写了python代码如下:

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)

但是,data.out 文件不包含任何内容。也就是说,子进程没有从其父进程继承stdin和stdout。但是当我写了一段c++代码如下:

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

我在data.out得到了正确答案,也就是说execv在c++代码中工作。

那么,我应该怎么做才能让 execv 在 python 中也能工作?我真的需要这个功能才能工作,有人可以告诉我吗?非常感谢!

data.in 包含以下内容:

1 1

【问题讨论】:

    标签: python fork stdout stdin execv


    【解决方案1】:

    在您的 Python 代码中,您已经打开了新的 IO 流,并将 sys.stdinsys.stdout Python 名称 设置为指向这些。它们将有自己的文件描述符(很可能是 3 和 4)。但是,标准文件描述符01 将保持不变,并继续指向它们的原始位置。这些是您在 C++ 程序中 exec 进入标准输入和标准输出时继承的描述符。

    您需要确保在执行之前调整实际的文件描述符。

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

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2017-08-18
      相关资源
      最近更新 更多