A small question about file descriptor

Can any body tell me when I put close(2), why the code does not show any out put?

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main(){

    int fd1,fd2,fd3,fd4;
close(2);
    fd1=open("test1.txt",O_WRONLY |O_CREAT | O_TRUNC,0744);
    fprintf(stderr,"fd1 = %d\n",fd1);


    fd4=open("test2.txt",O_WRONLY |O_CREAT | O_TRUNC,0744);
    fprintf(stderr,"fd4 = %d\n",fd4);
    
}

file descriptor 2 is stderr. You can do

printf ("%d\n", fileno (stderr)); 

to check

If you're closing stderr, and then fprintf'ing to stderr, you won't get any output.

Wow.Learned something new thanks dude.I am learning fd.I have another little question:
The following code use dup() to duplicate fd but my fd1=3, when I did fd2=dup(fd1) then why fd2 is not 3. My output shows fd2=4:

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main(){

    int fd1,fd2,fd3;
    fd1=open("test1.txt",O_WRONLY |O_CREAT | O_TRUNC,0744);
    fprintf(stderr,"fd1 = %d\n",fd1);
    
    
    fd2=dup(fd1);
    fprintf(stderr,"fd2 = %d\n",fd2);
    
    fd3=dup(fd2);
    fprintf(stderr,"fd3 = %d\n",fd3);

}

dup() duplicates an existing file descriptor (in this case fd=3) and returns
the new descriptor to the calling process. It does not close the existing
fiel descriptor.

The new descriptor returned by the call to dup() is the lowest numbered
descriptor currently not in use by the process (in this case fd=4)

Thanks for your answer.:slight_smile:

Two open fd's never share the same value. When you dup(), you just assure they'll read the same file. fd1 != fd2, but read(fd1, buf, sizeof (buf)) will return the same as read(fd2, buf, sizeof (buf)).