Home > Back-end >  Redirecting standard error to a file in c
Redirecting standard error to a file in c

Time:11-30

I am making my own shell in c and i am now trying to make a function which redirects the standard error of the shell to a specific file, an option which manages to show where the standard error is currently going to and anotherone able to reset the stderr to what it was originally.

I have implemented this code to redirect the stderr:

int fd, new_fd;
if((fd = open(tokens[1], O_RDWR)) == -1){
    perror("Error opening: ");
    return 0;
}
if(dup2(fd, STDERR_FILENO) == -1){
    perror("Error: ");
}
if(close(fd) == -1){
    perror("Error closing: ");
}

Now, I cant find anything for the option to restore or to show where the stderr is going to now, if someone could help me achieving this it would be amazing!

if(tokens[1] == NULL){
    //Shows where the standard error is currently going to

    return 0;
}

if(strcmp(tokens[1], "-reset") == 0){
    //Restores the standard error to what it was originally

    return 0;
}

CodePudding user response:

To restore stderr, save the original one to a new file descriptor using dup before replacing it. If you like you can later on restore it from that backup. If you don't do that and just replace it with the file you've opened, it will be lost as dup2 closes the descriptor it replaces and that way the only descriptor left for the old stderr was lost.

int backup = dup(STDERR_FILENO);
// ... later
dup2(backup, STDERR_FILENO);
  • Related