Dear All,
I've searched many topics and googled many web-pages, but still I didn't found solution to this problem.
I want to set timeout for connect(). The thing is, that my code works only on BSD, on Linux (tested on SuSE box) it freezes at connect() call
bool
SomeFunc(std::string rHost, unsigned int rPort, int rTimeout)
{
struct timeval timeout;
fd_set set;
int flags;
timeout.tv_sec = rTimeout;
timeout.tv_usec = 0;
MySocket sock;
sock.SetHostname(rHost);
sock.SetPort(rPort);
sock.socket();
try {
flags = fcntl(sock.GetSocket(), F_GETFL);
if (flags == -1) throw 1;
flags |= O_NONBLOCK;
fcntl(sock.GetSocket(), F_SETFL, flags);
FD_ZERO(&set);
FD_SET(sock.GetSocket(), &set);
flags = select(sock.GetSocket() + 1, &set, &set, &set, &timeout);
/*
int maxfd = max(maxfd, sock.GetSocket());
select(maxfd + 1, &set, &set, &set, &timeout);
FD_ISSET(sock.GetSocket(), &set);
*/
if (flags == -1) throw 2;
if (!sock.connect()) return false;
flags = fcntl(sock.GetSocket(), F_GETFL);
flags &= ~O_NONBLOCK;
fcntl(sock.GetSocket(), F_SETFL, flags);
}
catch (int n) {
log.log("can't set timeout, using system defaults (exp #" +
itos(n) + ", errno #" + itos(errno) + ")");
if (!sock.connect()) return false;
}
sock.disconnect();
return true;
}
MySocket is a C++ class, it's just a wrapper to such functions, like socket(), getservbyname(), etc.
I know, it is possible to use alarm() and such, but I don't want to use signals, because application is multithreaded. I've tried to implement timeout by using poll(), but I have no success with it.
I know, the solution is simple, but I can't find it
Thanks for your helping.