Search code examples
cfile-descriptor

How could I "turn on" stdout again?


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);

I want run a list of commands in file and store the result to another file. The code provided is the child. The parent is my shell asking user for input. The problem is that after executing this code,my parent's prompt ("Enter command:")is gone. I'm thinking it is caused by "close(1)". It closes stdout. What should I do to "turn on" stdout again?


Solution

  • Use:

    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);