Gilad Ben-Yossef <[EMAIL PROTECTED]> writes:

> Oleg Goldshmidt wrote:
> 
> > Purely from memory, it is POSIX, though I would use STDOUT_FILENO
> > or fileno(stdout).
> 
> OK. I see I wasn't clear about what i was asking.

Not to me, but that's my problematic internal parser. Obviously I read
the question as "is fd 1 guaranteed to be stdout?". I should have
given you the credit of knowing that even when you are really tired.
I apologize. I was tired... ;-)

Apparently, there is no guarantee that the operation in the test will
succeed (see below). I suspect that on most platforms std{in,out,err}
(or whatever the macros expand to) are static, and maybe there are
platforms that return those pointers from fdopen().

At least it is not the case with glibc on Linux:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {

        int rc = 0;
        int newfd;
        FILE* new = NULL;
        char file[PATH_MAX] = "/tmp/fd";
        
        fprintf(stderr,"stdout: %p (initial)\n", (void*)stdout);

        if ((newfd = dup(fileno(stdout))) == -1) {
                perror(strerror(errno));
                rc = 1;
                goto CLEAN_UP;
        }

        if (freopen(file,"w",stdout) == NULL) {
                perror(strerror(errno));
                rc = 2;
                goto CLEAN_UP;
        }

        fclose(stdout);

        fprintf(stderr,"stdout: %p (closed)\n", (void*)stdout);
        
        if (dup2(newfd,1) != 1) {
                perror(strerror(errno));
                rc = 3;
                goto CLEAN_UP;
        }
                
        if ((new = fdopen(1,"w")) == NULL) {
                perror(strerror(errno));
                rc = 4;
                goto CLEAN_UP;
        }
        
        fprintf(stderr,"new:    %p\n", (void*)new);
        fprintf(stderr,"stdout: %p (final)\n", (void*)stdout);
        
 CLEAN_UP:
        
        return rc;
}


produces

$ ./a.out
stdout: 0x4212db00 (initial)
stdout: 0x4212db00 (closed)
new:    0x8049b80
stdout: 0x4212db00 (final)

It does look like a bug.

-- 
Oleg Goldshmidt | [EMAIL PROTECTED]

=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]

Reply via email to