2014-04-11 109 views
0
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); 

我想运行文件中的命令列表并将结果存储到另一个文件中。提供的代码是孩子。父母是我的外壳,要求用户输入。问题是执行此代码后,我的父母的提示(“输入命令:”)消失了。我认为这是由“close(1)”造成的。它关闭stdout。我应该怎么做才能再次打开stdout?我怎样才能“再次打开”标准输出?

回答

2

用途:

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); 
相关问题