Linux判断文件描述符是否有效

来源:互联网 发布:多级分销数据库 编辑:程序博客网 时间:2024/06/06 18:29

Linux判断文件描述符是否有效

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * author:kangear@163.com  
  3.  * date  :2015-01-17 
  4.  * func  :check if the fileDescriptor is fine. 
  5.  */  
  6.   
  7. #include <unistd.h>  
  8. #include <fcntl.h>  
  9. #include <sys/types.h>  
  10. #include <sys/stat.h>  
  11. #include <fcntl.h>  
  12. #include <errno.h>  
  13.   
  14. int main() {  
  15.     int fd = -1;  
  16.     fd = open("/tmp/isatty.c", O_RDONLY);  
  17.     // close(fd);  
  18.     if(fcntl(fd, F_GETFL))  
  19.         printf("%m\n");  
  20.     close(fd);  
  21. }  

[cpp] view plaincopy
  1. /** 
  2.  * version : 1.1 
  3.  *    date : 2015-02-05 
  4.  *    func : check if the fileDescriptor is fine. 
  5.  */  
  6.   
  7. #include <unistd.h>  
  8. #include <fcntl.h>  
  9. #include <sys/types.h>  
  10. #include <sys/stat.h>  
  11. #include <fcntl.h>  
  12. #include <errno.h>  
  13. #include <sys/types.h>  
  14. #include <sys/stat.h>  
  15. #include <unistd.h>  
  16. #include <stdio.h>  
  17.   
  18. struct stat _stat;  
  19.   
  20. /** 
  21.  * On success, zero is returned.  On error, -1  is  returned,  and  errno  is  set 
  22.  *      appropriately. 
  23.  */  
  24. int check_fd_fine(int fd) {  
  25.     struct stat _stat;  
  26.     int ret = -1;  
  27.     if(!fcntl(fd, F_GETFL)) {  
  28.         if(!fstat(fd, &_stat)) {  
  29.             if(_stat.st_nlink >= 1)  
  30.                 ret = 0;  
  31.             else  
  32.                 printf("File was deleted!\n");  
  33.         }  
  34.     }  
  35.     if(errno != 0)  
  36.         perror("check_fd_fine");  
  37.     return ret;  
  38. }  
  39.   
  40. int main() {  
  41.     int fd = -1;  
  42.     fd = open("/dev/ttyUSB1", O_RDONLY);  
  43.     if(fd < 0) {  
  44.         perror("open file fail");  
  45.         return -1;  
  46.     }  
  47. //  close(fd);  
  48.     sleep(5);  
  49.     if(!check_fd_fine(fd)) {  
  50.         printf("fd okay!\n");  
  51.     } else {  
  52.         printf("fd bad!\n");  
  53.     }  
  54.     close(fd);  
  55.     return 0;  
  56. }  
0 0
原创粉丝点击