Search code examples
linuxunixfile-descriptor

linux programming: value of file descriptor is always 3


I'm new to linux programming. I wrote a very simple program:

#include stdio.h
#include fcntl.h
#include sys/ioctl.h
#include mtd/mtd-user.h
#include errno.h

int main( void )
{
    int fd;

    fd = open("test.target", O_RDWR);
    printf("var fd = %d\n", fd);
    close(fd);
    perror("perror output:");

    return 0;
}

test.target is created just using touch command. the program's output is:

var fd = 3
perror output:: Success

I've tried to open other files, and the file descriptor was always 3.I remembered it's value should be a larger number.If this program has some errors?


Solution

  • This seems normal. Processes start with pre-opened file descriptors: 0 for stdin, 1 for stdout and 2 for stderr. Any new files you open should start with 3. If you close a file, that file descriptor number will be re-used for any new files you open.