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

前端 未结 6 1006
孤独总比滥情好
孤独总比滥情好 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:51

    I don't think there is any function that can tell you if the descriptor is still valid. The descriptor is typically just a small integer like 6 and your libc can choose to reuse that number if you close the file and open a new one later.

    Instead, you should consider using dup() to copy the file descriptor. By duplicating the file descriptor instead of using the same descriptor in multiple places, it might become easier for you to know whether the file descriptor is still valid. You just have to remember to close both the original descriptor and the duplicated one when you are done.

提交回复
热议问题