Timeout in UNIX

How do you implement a timeout in Unix???
Let me explain what I am trying to do:
I've opened a device file (serial port - connected to a modem) for I/O. I am communicating with a terminal (phone) which also has a modem. I need to wait for a response from the terminal after having sent a command. So I do a 'write' to the device file to send the command to the terminal, and do a 'read' from the device to get the response. I want to wait, let us say, only 15 seconds for the response, HOW DO I DO IT?
I am using the standard 'read' and 'write' routines.                                
Who is Participating?
kamathConnect With a Mentor Commented:
there is a system call called *select* in UNIX. you can define a file descriptor set and a filter and specify a timeout:

Look out man pages for select
also here is a code that does it:
 // Reference   : C Library function select(3C)
   fd_set readfds;
   FD_SET(mSocket,   &readfds);
   struct timeval timeout;
   timeout.tv_sec = mReceiveTimeout;
   timeout.tv_usec   = 0;
   int numFds =   select(mSocket+1, &readfds, 0, 0, &timeout);
   int numReceived   = 0;

   // If an error occurred, deal with it
   if (numFds == -1)
   // Read  the   input, if available
   else  if  (numFds  ==   1)
      int ret  = recv(mSocket,    aBuf, aBufSize,   0);
      if (ret  == -1)
      else /*  if (ret  != -1) */
         numReceived = ret;
   // Otherwise, there was a timeout
   else  if  (numFds  ==   0)

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.