Skip to content
Advertisement

C – get list of opened handlers – duplicate entries

I have this code to retrieve list of opened handlers (mostly FILE)

int flags;
int fd;
char buf[MAXPATHLEN+1] ;
int n = 1 ;

for (fd = 0; fd < (int) FD_SETSIZE; fd++)
{
    errno = 0;
    flags = fcntl(fd, F_GETFD, 0);
    if (flags == -1 && errno)
    {
        if (errno != EBADF)
        {
            return;
         }
     }

     fcntl(fd , F_GETPATH, buf ) ;
     printf( "File Descriptor %d number %d in use for: %s",fd,n , buf ) ;
    ++n ;
}

However, when i call single fopen and run this, it prints the same file multiple times (from n to FD_SETSIZE, where n is some offset id… first 0 .. n are some system handlers like dev/nul etc.).

Advertisement

Answer

Your error check after fcntl(fd, F_GETFD, 0) is a bit suspect. Assuming your intent is to bail after you hit the first bad fd, then the check should be errno == EBADF.

Also, I suggest checking result of your second fcntl before printf

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement