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

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, ....);

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) 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.

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.

Need Your Help

How to loop API Calls Swift after parsing data

ios swift api loops

I'm currently making an API call to return a bunch of JSON data, parsing it, and then sorting it based on a few different criteria. After the JSON data is parsed (it pulls back a bunch of recipes),...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.