Tuesday, March 27, 2012
C++: Imlpementing a PHP styled, timeout enabled,Socket wrapper funtion for C/C++ accept()
I'm relatively new to C++ and learning it was a tougher challenge (i'm still learning it by the way ;)) than learning other "newer" languages, it really surprised me that a developer should go out of his way to implement even the most trivial functionsin order to achieve his main objective, which is in violation with the concept of OOP and encapsulation. With so many seasoned veterans using C/C++ around, I wonder how they all turn a blind eye to this issue.
A recent project i did required me to implement a socket server that keeps listening for an incoming connection, if a request arrives within a certain time window it should serve it else should timeout and proceed with a little bit of housekeeping after which it should loop back to socket accept. But when implementing this i had much trouble trying to figure out how to find a way to set timeout on accept().
I found a piece of code in Solaris programming interfaces guide which offered a method (platform used for the project is Solaris)
(docs.oracle.com/cd/E19253-01/817-4415/817-4415.pdf)
Timeout is achieved using select() function, which allows us to instruct kernel to wait for any one of multiple event to occur and proceed once one or more events had happened. I wanted a PHP style accept() function for C++ so i modified the version given in the above document to create wrapper function for C++ accept() called socket_accept() as below.
The timeout is a timeval type structure pointer passed to it by the caller. Following code shows how it should be defined(5 seconds and 0 micro seconds).
and then call it in main() as below,
Labels:
C,
C++,
socket timeout,
socket_select,
sockets api
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment