perror and strerror with close(2) involved

449 Views Asked by At

I have this code with close(2) implemented, as many of you know(including myself) this closes the standard error, but what are the main repercussions of closing it?

And why is "main: Success" printed? Shouldn't every directory have the "." dir that can be opened?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>


int main() {
    close(2);
    if (fopen(".","r")) 
    {
        printf("main: %s \n", strerror(errno));
    }
    return 0;
}

On the other hand

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main() {
    close(2);
    if (fopen(".","r")) 
    {
        perror("main");
    }  
    return 0;
}

This doesn't print anything, any ideas why?

2

There are 2 best solutions below

0
On BEST ANSWER

Standard error is where error messages are supposed to be printed. So perror() prints its error message on standard error. If you close standard error, it can't print the message.

Why is "main: Success" printed? Shouldn't every directory have the "." dir that can be opened?

Yes, it does. You didn't get an error when calling fopen(), so errno == 0, and the message for this is Success.

If you want to print an error message when fopen() fails, you need to test for NULL:

if (fopen(".") == NULL) {
    printf("main: %s \n", strerror(errno));
}

Note that when opening files, the FD that's used is the lowest available FD. Since you've closed FD 2, that will most likely be used when opening .. So standard error now points to the . directory, which you can't write to, and perror() will get an error when it tries to write there. But it can't report this error (where would it report it?).

0
On

what are the main repercussions of closing it?

Undefined Behavior. The C standard says "The behavior is undefined in the following circumstances: [...] The value of a pointer to a FILE object is used after the associated file is closed", and POSIX says "The stderr stream is expected to be open for reading and writing."