C “我怎么可能?”;打开";又是stdout?

C “我怎么可能?”;打开";又是stdout?,c,file-descriptor,C,File Descriptor,我想在文件中运行命令列表,并将结果存储到另一个文件中。提供的代码是子对象。父对象是我的shell,请求用户输入。问题是,在执行此代码后,我的父级提示符(“Enter命令:”)消失了。我认为这是由“关闭(1)”引起的。它关闭了stdout。我应该怎么做才能再次“打开”标准输出 使用: int fd_redirect_to = open(token, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); close(1); //close stdout dup(fd_redi

我想在文件中运行命令列表,并将结果存储到另一个文件中。提供的代码是子对象。父对象是我的shell,请求用户输入。问题是,在执行此代码后,我的父级提示符(“Enter命令:”)消失了。我认为这是由“关闭(1)”引起的。它关闭了stdout。我应该怎么做才能再次“打开”标准输出

使用:

int fd_redirect_to = open(token, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
close(1); //close stdout

dup(fd_redirect_to); //new out
char* line=NULL;
size_t len=0;

while( getline(&line,&len,input_f)!=-1 )
{

    line[strlen(line)-1]='\0'; //get rid of next line

    char* arg[20]; //the most 20 arguments
    int i=0;
    char* token=NULL;

    token=strtok(line,del);
    while(token)
    {
        arg[i]=strdup(token);
        ++i;
        token=strtok(NULL,del);
    }

    arg[i]=(char*)0;

    pid_t div=fork(); //give its own process
    if(div==0)
        execvp(arg[0],arg);
    else if(div>0);
    else
        printf("error");
}
close(fd_redirect_to);
int saved = dup(STDOUT_FILENO);
close(STDOUT_FILENO);
dup2(fd_redirect_to, STDOUT_FILENO);

... Now all stdout will go to fd_redirect_to

... Now recover

dup2(saved, STDOUT_FILENO);