Hello,
Allow me to explain my full problem. Hopefully you'll agree that
select() is the way to go and possibly shed some light on why it isn't
working.
I have a process that, when started, listens for incoming connections.
If someone connects to the process, it starts up a few other
processes and goes about listening for another connection. All of
this works fine (I used a blocking socket for all of it). But I now
need the process to kill itself when the user logs off. After much
surfing of this usegroup and the internet, I've realized that I need a
non-blocking socket for the accept() call so that I can loop and
occasionally test to see if the parent process has been killed (which
would be the shell, and then I'd kill the program itself). The SIGHUP
signal isn't an option because it doesn't send it to my process when
it's running in the background.
All right, so there's my goal. Now, I figure what I'll do is use a
non-blocking socket, loop using select() with a timeout value so that
I'd be testing to see if the process should commit suicide every X
seconds. I've gotten the code down, but here's my problem. I start
up the program (call it the console) and when I go to start the other
program (which will connect to the console) it doesn't work, the
console never realizes a connection is being attempted. It does work,
however, if my timeout value is NULL. Here's my code for accepting a
connection:
fcntl(ListenSocket, F_SETFL, O_NONBLOCK);
fd_set set;
FD_ZERO(&set);
FD_SET(ListenSocket, &set);
struct timeval tv;
for (;;)
{
tv.tv_sec = 5;
tv.tv_usec = 0;
int retval;
// works fine if &tv is replaced with NULL
if ((retval = select(ListenSocket+1, &set, &set, NULL, &tv))>0)
{
sockaddr_in sinRemote;
int nAddrSize = sizeof(sinRemote);
Socket = accept(ListenSocket, (sockaddr*)&sinRemote, (socklen_t
* &nAddrSize);
if (Socket==-1)
{
if (errno==EWOULDBLOCK)
{
continue;
}
else
{
return 0;
}
}
else
{
fcntl(ListenSocket, F_SETFL, 0);
return 1;
}
}
else if (retval==0)
{
// This is where i'd check to see if the user has logged out
continue;
}
else
{
return 0;
}
}
return 0;