next up previous contents index
Next: Buffered, stream-oriented communication. Up: Socket I/O Previous: Error codes.   Contents   Index

Timeouts.

XSB socket interface allows the programer to specify timeouts for certain operations. If the operations does not finish within the specified period of time, the operation is aborted and the corresponding predicate succeeds with the TIMEOUT_ERR error code. The following primitives are timeout-enabled: socket_connect/4, socket_accept/3, socket_recv/3, socket_send/3, socket_get0/3, and socket_put/3. To set a timeout value for any of the above primitives, the user should execute set_timer/1 right before the subgoal to be timed. Note that timeouts are disabled after the corresponding timeout-enabled call completes or times out. Therefore, one must use set_timer/1 before each call that needs to be controlled by a timeout mechanism.

The most common use of timeouts is to either abort or retry the operation that times out. For the latter, XSB provides the sleep/1 primitive, which allows the program to wait for a few seconds before retrying.

The set_timer/1 and sleep/1 primitives are described below. They are standard predicates and do not need to be explicitly imported.

set_timer(+Seconds)

Set timeout value. If a timer-enabled goal executes after this value is set, the clock begins ticking. If the goal does not finish in time, it succeeds with the error code set to TIMEOUT_ERR. The timer is turned off after the goal executes (whether timed out or not and whether it succeeds or fails). This goal always succeeds.

Note that if the timer is not set, the timer-enabled goals execute ``normally,'' without timeouts. In particular, they might block (say, on socket_recv, if data is not available).

sleep(+Seconds)

Put XSB to sleep for the specified number of seconds. Execution resumes after the Seconds number of seconds. This goal always succeeds.
Here is an example of the use of the timer:
:- compiler_options([xpp_on]).
#include "timer_defs_xsb.h"

?- set_timer(3),  % wait for 3 secs
   socket_recv(Sockfd, Msg, ErrorCode),
   (ErrorCode == TIMEOUT_ERR
   -> writeln('Socket read timed out, retrying'),
      try_again(Sockfd)
   ;  write('Data received: '), writeln(Msg)
   ).

Apart from the above timer-enabled primitives, a timeout value can be given to socket_select/6 directly, as an argument.


next up previous contents index
Next: Buffered, stream-oriented communication. Up: Socket I/O Previous: Error codes.   Contents   Index
Luis Fernando P. de Castro 2003-06-27