首先,我写了一个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