views:

4250

answers:

4

Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?

I.e. I want to set a timeout on blocking socket in boost asio?

socket.read_some(boost::asio::buffer(pData, maxSize), error_);

Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed.

A: 

On *nix, you'd use alarm() so your socket call would fail with EINTR

Paul Betts
Wouldn't all your socket calls, in all your threads fail with EINTR?That sounds bad.
Rhythmic Fistman
+2  A: 

http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/example/timers/time_t_timer.cpp

HTH

plan9assembler
That is async. The question was specific to sync.
Brian R. Bondy
no, it isn't, the timer used for both methods, sync, async. re-read the example.
plan9assembler
+3  A: 

Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via setsocktopt(). I don't know if boost::asio provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable.

For a sake of completeness here's the description from the man page:

SO_RCVTIMEO and SO_SNDTIMEO

          Specify the receiving or sending  timeouts  until  reporting  an
          error.  The argument is a struct timeval.  If an input or output
          function blocks for this period of time, and data has been  sent
          or  received,  the  return  value  of  that function will be the
          amount of data transferred; if no data has been transferred  and
          the  timeout has been reached then -1 is returned with errno set
          to EAGAIN or EWOULDBLOCK just as if the socket was specified  to
          be  non-blocking.   If  the timeout is set to zero (the default)
          then the operation  will  never  timeout.   Timeouts  only  have
          effect  for system calls that perform socket I/O (e.g., read(2),
          recvmsg(2), send(2), sendmsg(2)); timeouts have  no  effect  for
          select(2), poll(2), epoll_wait(2), etc.
Nicola Bonelli
This would be a great solution, but they don't have such socket options. See socket options here: http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/reference.html
Brian R. Bondy
Boost are good but not perfect :-)
Nicola Bonelli
+1  A: 

You could do an async_read and also set a timer for your desired time out. Then if the timer fires, call cancel on your socket object. Otherwise if your read happens, you can cancel your timer. This requires you to use an io_service object of course.

edit: Found a code snippet for you that does this

http://lists.boost.org/Archives/boost/2007/04/120339.php

grepsedawk