How to check if a given file descriptor stored in a variable is still valid?

前端 未结 6 1000
孤独总比滥情好
孤独总比滥情好 2020-11-29 01:17

I have a file descriptor stored in a variable say var. How can I check whether that descriptor is valid at a later stage?

  fdvar1= open(.....);
  fdvar2 =          


        
6条回答
  •  北海茫月
    2020-11-29 01:45

    From this forum article:

    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. In particular, the specification suggests that it cannot be interrupted by signals, nor is it affected by any sort of lock held anywhere.

提交回复
热议问题