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);
我想在文件中运行命令列表并将结果存储到另一个文件中。提供的代码是孩子。父亲是我的shell,要求用户输入。问题是在执行此代码后,我父母的提示("输入命令:")消失了。我认为它是由" close(1)"引起的。它关闭stdout。我应该怎么做"打开" stdout又来了?
答案 0 :(得分: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);