LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Asynchronous accept() with posix sockets. (http://www.linuxquestions.org/questions/programming-9/asynchronous-accept-with-posix-sockets-891070/)

BartekBl 07-11-2011 06:50 AM

Asynchronous accept() with posix sockets.
 
Hi! I know it is possible to use asynchronous I/O with read/write, but is it possible to accept incoming connections when they arrive and still do other things in the meantime without using multithreading and without having to periodically check with accept function (non-blocking mode)?

Usually you do sth like this:

Code:

int main()
{
  socket(sock, ...)
  bind(sock, ...)
  listen(sock, ...)
  while (run)
  {
    accept(sock, ...0;
    spawn_thread(); //or fork()
  }
}

I'd like to do sth like this:

Code:

void func()
{
  spawn_thread();
}

int main()
{
  socket(sock, ... , ASYNC)
  bind(sock, ...)
  listen(sock, ...)
  enable_SIGIO(); //or other proper signal
  accept(sock, ..., func);
  while (run)
  {
    sleep(1);
  }
}

It doesn't necessarily have to be posix, the target is Linux 2.6

wje_lq 07-11-2011 03:43 PM

If you're willing to use a select() loop, then:
  1. Open the listening socket in async mode (O_NONBLOCK).
  2. Set up the loop in the normal manner.
  3. Before going into the loop, do the listen().
  4. Each time through the loop, add the listening socket to the read fd's, but not to the write fd's.
  5. When an accept() is possible, then the select() will say that you can "read" on the listening socket.

BartekBl 07-12-2011 03:13 AM

AFAIK I could as well use accept with non-blocking mode to poll for waiting connections, but still its non blocking and what I want is asynchronous (like receving SIGIO whenever someone tries to connect so that I can accept it). Unfortunatelly due to some hardware problems I can't test it now. Thanks for your help anyway.

EDIT: I think that I what I want can't be done :( marking the thread as solved.


All times are GMT -5. The time now is 03:33 AM.