Link to home
Start Free TrialLog in
Avatar of xofrats
xofrats

asked on

problem with accept() in C

I am creating a simple chat program in C. In my server program I have a code that accepts connections using accept(). My problem is that accept() waits for an incomming connection and I cannot proceed to the other statements. Why is this and how can I fix it?
ASKER CERTIFIED SOLUTION
Avatar of markdoc
markdoc

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sunnycoder
>My problem is that accept() waits for an incomming connection and I cannot proceed to the other statements. Why is this
As markdoc said, accept blocks for input connections and that is expected behavior.
>and how can I fix it?
you can have a non-blocking accept but that is not a good idea ... Select will also not be very helpful in this regard ... The best way here might be to go in for multithreading ... Let your main thread listen for connections and accept them. Upon accepting, it can spawn a thread and threads can process that connection send()ing and recv()ing in a separate control flow.

Somethig like

main()
{
    ....
    ....
    while (1)
    {
       sock=accept()
        ...
        create_thread(... sock, thread_func, ...)
        ...
     }
    ...
}

thread_func( ... sock ...)
{
      ...
      send()
       ...
      recv()
      ...
}

You can chose any thread library available on your platform.

Cheers!
sunnycoder
Avatar of Nikhil Gupta
Nikhil Gupta

you can try multiple process also.
 try this code.
if(fork()!=0)
{
 //parent will wait for new connection.
 sock_fd=accept();

}
else
{
   //this is child process.
  //put your stuff here
}