473,834 Members | 2,148 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Detecting if a file descriptor is closed

7,872 Recognized Expert Expert
I'm having a bit of trouble figuring out how to detect if a socket is closed or not. Outside of using read()/write(). I also don't want to set the socket to non-blocking if at all possible.
I wrote a function that reads a single char(or byte, whatever) and wanted to use it in a simulated blocking and nonblocking way.
It works fine for waiting for the correct timeouts, but since I use ioctl() to detect if there is data to be read, I won't actually call the read() method that would show me the socket is closed.

I was thinking there was some way to detect "can write" or "can read" on a file descriptor without going into a blocking state, but I can't find it if there is one.

Expand|Select|Wrap|Line Numbers
  1. read_ret_t ReadChar(int sock, int milisecondTimeout, char &refchar)
  2. {//-1=errors, 0=closed, 1=timeout, ?=ok?
  3.   enum read_ret_t retval=ERRORED ;
  4.   char buf[10]={0x00};
  5.   char nbyte[10]={0x00};
  6.   int numofwaits=0;
  7.   if(milisecondTimeout!=0)
  8.   {// "non-blocking"
  9.     refchar=0x00;
  10.     while(numofwaits<milisecondTimeout)
  11.     {
  12.       int bytestoread=0;
  13.       int d=ioctl(sock, FIONREAD, &bytestoread);//should do error checking on return value of this
  14.       if(d!=0)printf("ioctl()=%d\r\n",d);
  15.       //int fd=write(sock,nbyte,1);//writing a single 0x00 byte can trigger fd=-1 when closed
  16.       if(bytestoread>0)
  17.       {
  18.         int res=read(sock,buf,1);
  19.         if (res<0)
  20.         {retval=ERRORED;}
  21.         else if(res==0)
  22.         {retval=CLOSED;}
  23.         else
  24.         {retval=OK;}
  26.         refchar=buf[0];
  27.         break;
  28.       }
  29.       else
  30.       {
  31.         usleep(1000);//1000uSecs = one milisec
  32.         numofwaits=numofwaits+1;
  33.       }
  34.     }
  35.     if (numofwaits>=milisecondTimeout)
  36.     {
  37.       retval=TIMEDOUT;
  38.     }
  40.   }
  41.   else
  42.   {//blocking
  43.     int res=read(sock,buf,1);
  44.     if (res<0)
  45.     {retval=ERRORED;}
  46.     else if(res==0)
  47.     {retval=CLOSED;}
  48.     else
  49.     {retval=OK;}
  51.     refchar=buf[0];
  52.   }
  54.   return retval;
  55. }
Any thoughts on a non-blocking way to detect if a blocking call has timed out?

I toyed with changing the socket option of receive timeouts to a very small time and using like recv with the PEEK option, but that seemed like the wrong way to go.
Mar 11 '09 #1
11 18058
256 Contributor
My memory is really fuzzy on this topic, but I think I've accomplished something like this in the past by setting a timer, then calling read(). Then if the timer expires you get an interrupt, which makes the read fail, setting errno appropriately. That way you can just start the read and if the socket is closed you'll get that error too and you wont have to worry about blocking for too long.

I can't for the life of me remember how to accomplish timers in C and my usual references aren't handy at the moment.
Mar 12 '09 #2
11,448 Recognized Expert MVP
If you don't want to use a read() call on the socket (the read() might succeed if the socket is still open and connected and where should the byte be put?) you can call a select on that single file/socket descriptor; if the socket is not connected and not ready for a read the errno variable is set to EBADF and the select() function will return -1 (if I'm not mistaken).

kind regards,

Mar 12 '09 #3
7,872 Recognized Expert Expert
I was looking at the select function, but it seemed to have a lot of structs and overhead and I wasn't even sure it would tell me what i wanted.
It also said it was a blocking call
FD_ISSET doesn't change between open and closed fd

Ok, so select can be given a timeout, and it behaves a lot like Poll() does in C# (I imagine Poll just calls select)
Seems that checking for writable/exceptional never changes, but checking for readable will trigger if their is data to be read of if the socket is closed.
And since I have another check already to see if there is data, I can combine them to find out.

Thanks for all the help!
Mar 12 '09 #4
11,448 Recognized Expert MVP
Yep, if doesn't change those flags when an error occurs; check for the return status of select() and the errno variable. Those sets are simply bit sets with a bit set for every file descriptor number, e.g. bit 0 is set for stdin. FD_ISSET simply checks for a particular bit value; the FD_SET and FD_CLR macros (re)set that particular bit.

kind regards,

Mar 12 '09 #5
7,872 Recognized Expert Expert
For those who are interested, here is what I have:

Expand|Select|Wrap|Line Numbers
  1. bool isClosed(int sock)
  2. {
  3.   bool retval =false;
  4.   int bytestoread=0;
  5.   fd_set myfd;
  7.   FD_ZERO(&myfd);
  8.   FD_SET(sock,&myfd);
  9.   int sio=select(FD_SETSIZE,&myfd, (fd_set *) 0,(fd_set *) 0, &timeout);
  10.   //have to do select first for some reason
  11.   int dio=ioctl(sock, FIONREAD, &bytestoread);//should do error checking on return value of this
  12.   retval=((bytestoread==0)&&(sio==1));
  14.   return retval;
  15. }
Mar 12 '09 #6
11,448 Recognized Expert MVP
Isn't select() supposed to return -1 when the descriptor is closed?

kind regards,

Mar 12 '09 #7
7,872 Recognized Expert Expert
Maybe if it is closed on the local side, but since i am using a socket, it could be closed remotely
Mar 12 '09 #8
11,448 Recognized Expert MVP
But in that case a read would simply fail; isn't your software prepared for that event? i.e. no more data can be read ...

kind regards,

Mar 12 '09 #9
7,872 Recognized Expert Expert
Yes, if I actually DO a read, I would get the failure message, but since I only do a read if there is data there to be read, that is where the problem arises. And thus, the select() call
Mar 12 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Bryan | last post by:
i'm curious to know how others handle the closing of files. i seem to always end up with this pattern even though i rarely see others do it. f1 = file('file1') try: # process f1 finally: f1.close() which explicitly closes f1
by: John Marshall | last post by:
Hi, Does anyone see a problem with doing: data = file("tata").read() Each time this is done, I see a new file descriptor allocated (Linux) but not released. 1) Will there ever be a point where I
by: Marco Nicosia | last post by:
Hello gang, My coworker and I are writing a Python class for the other developers within our team. This class is supposed to encapsulate several things, including daemonizing, setting up logging, and spawning a thread to host an XML-RPC server. I'm having a real problem with logging.Logger and threading.Thread. In the main thread, we set up two loggers, each with file handlers. We then spawn the xml-rpc server thread, and allow the...
by: Sagaert Johan | last post by:
I have a program that uses the filesystemwatcher. Problem is that i have to wait until the file is closed before i can do someting with it in the changed event. How can i detect if the foreighn application has finished writing and has closed the file ? Johan
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified folder structure and naming conventions and then send a Net send message to those users telling them to rectify. The information I want to get is when you select the file/folder and then: Properties -> Security Tab -> Advanced Button -> Owner Tab ->...
by: Didier Trosset | last post by:
I am using the following code. It is used to spawn a new process (using popen) and to change the file handles so that subsequent writes to standard output with printf goes into this child process standard input. import os child_stdin = os.popen("cat -", "w") old_stdout = os.dup(1) os.close(child_stdin.fileno())
by: nik | last post by:
Hi, How can I close a thread that is waiting on a file/port down gracefully, and not have an IO error pop up? I am having trouble closing a thread that is listening to the serial port. I have a thread that calls uses a pySerial serial port and calls readline() without a timeout, which is blocking. When I am shutting down the application I close the serial port, which causes the IO error: (9, 'Bad file descriptor'). It makes sense that...
by: yinglcs | last post by:
I have a c/c++ program in linux. I would like to know if I kill my program (e.g. exit(1)), will it release all the file descriptors my program held (regardless if I call close(fd) of each file descriptor)? Thank you.
by: =?ISO-8859-15?Q?L=E9na=EFc?= Huard | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all, For some reasons, somewhere in a program, I'd like, if possible, to quickly parse a whole file before rewinding it and letting the full analysis start. My problem is that the FILE* I want do parse has been fopen'ed far away from where I am and I don't know in which MODE my FILE* has been opened. And additionally, my FILE* may not be a regular file, but a continuous
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.