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

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

    i solved this problem for me. i don't know whether it can be used for general purpose but for serial connections it works fine (e.g. /dev/ttyUSB0)!

    struct stat s;
    fstat(m_fileDescriptor, &s);
    
    // struct stat::nlink_t   st_nlink;   ... number of hard links 
    if( s.st_nlink < 1 ){
     // treat device disconnected case
    }
    

    For details see e.g. man page http://linux.die.net/man/2/fstat

    Cheers, Flo

提交回复
热议问题