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

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

问题描述

我有一个文件描述符存储在一个变量中,比如 var.如何在稍后阶段检查该描述符是否有效?

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 是否为有效打开文件描述符的最廉价的规范方法.如果您需要批量检查很多,使用 poll 和零超时和 events 成员设置为 0 并检查 POLLNVALrevents 返回后效率更高.

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 是 closed),它的值可能会重新分配给您分配的下一个此类资源.如果有可能使用的任何剩余引用,它们将错误地操作新资源而不是旧资源.因此,真正的答案可能是:如果您还不知道程序的逻辑,那么您就有需要修复的主要基本逻辑错误.

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天全站免登陆