Thread: Checking if a file descriptor is valid

  1. #1
    Registered User
    Join Date
    Jun 2007

    Checking if a file descriptor is valid

    Hey, does anybody know how to check whether the file descriptor is valid?

  2. #2
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Banks of the River Styx
    You might need to clarify that question a bit...

    Functions like open() will return a certain value (-1) for failure. Otherwise, the easiest way is that it's up to you to keep track of file descriptors.

    Alternatively, if you're in Linux, you could read your process's dir in /proc, but again, this all depends - what are you wanting to do?
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  3. #3
    Registered User
    Join Date
    Oct 2007
    there are two ways to achieve this:

    1. check for the return value when returned from open() system call.

    int fdesc;
    if(fdesc = open(//arguments) == -1)

    2. the other way is ioctl() system calls and check the inode file structure.

    Hope i answered your query...

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    To just see if a file descriptor is valid you could use this:
    int is_valid_fd(int fd)
        return fcntl(fd, F_GETFL) != -1 || errno != EBADF;
    fcntl(GETFL) is probably the cheapest and least likely to fail operation you can perform on a file descriptor, so I've chosen it. In particular, the specification suggests that it cannot be interrupted by signals, nor is it affected by any sort of lock held anywhere.
    All the buzzt!

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM