如何检查是否存储在变量中给定的文件描述符仍然有效? [英] How to check if a given file descriptor stored in a variable is still valid?

查看:149
本文介绍了如何检查是否存储在变量中给定的文件描述符仍然有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储在一个变量文件描述符说变种。我如何检查描述符是否是有效的在后一阶段?

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 = fdvar1;       // Please ignore the bad design

  ....
  // lots of loops , conditionals and threads. It can call close(fdvar2) also.  
  ....

  if(CheckValid(fdvar1)) // How can I do this check  ?
    write(fdvar1, ....);

现在我要检查VAR1(它仍然保持着打开描述符)是否仍然有效。
任何API的是什么?

Now i want to check whether var1 (which still holds the opened descriptor) is still valid. Any API's for that ?

推荐答案

的fcntl(FD,F_GETFD) 是检查 FD 是一个有效的打开文件描述符规范的最便宜的方式。如果需要批量查了很多,使用调查以零超时和事件成员设置为0,在的revents 检查 POLLNVAL 返回后更加高效。

fcntl(fd, F_GETFD) is the canonical cheapest way to check that fd is a valid open file descriptor. If you need to batch-check a lot, using poll with a zero timeout and the events member set to 0 and checking for POLLNVAL in revents after it returns is more efficient.

随着中说,运作的检查,如果给定的资源句柄仍然有效几乎总是从根本上不正确。经过资源句柄被释放(例如,fd是关闭 D),它的价值可能被重新分配给你分配的下一个这样的资源。如果有可能被使用的任何剩余的引用,就会错误地在新的资源,而不是旧的操作。因此,真正的答案可能是:如果你还没有你的程序的逻辑都知道,你有需要修复的主要基本的逻辑错误

With that said, the operation "check if a given resource handle is still valid" is almost always fundamentally incorrect. After a resource handle is freed (e.g. a fd is closed), its value may be reassigned to the next such resource you allocate. If there are any remaining references that might be used, they will wrongly operate on the new resource rather than the old one. Thus, the real answer is probably: If you don't already know by the logic of your program, you have major fundamental logic errors that need to be fixed.

这篇关于如何检查是否存储在变量中给定的文件描述符仍然有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆