dup2 作用是复制文件句柄
int dup2(int oldhandle,int newhandle);
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
void run(){
int fd[2];
pipe(fd);
pid_t pid;
pid = fork();
if (pid == 0) //child process
{
fd[0] =open("inputfilename",O_RDONLY);
dup2(fd[0], STDIN_FILENO);
execvp(...);
}
if (pid > 0) //parent process
{
dup2(fd[1],STDOUT_FILENO);
execvp(...);
}
}
int main(){ run (); return 0;}
当然文件的输入输出重定向也可以用freopen。