Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

Non-blocking sockets

&pagelevel(3)&pagelevel

With non-blocking sockets, the accept(), connect() and all input/output functions are terminated if they cannot be executed immediately. The function concerned then returns an error code. This means that, in contrast to normal sockets, non-blocking sockets prevent a process from being stopped because it has to wait for termination of accept(), connect() or input/output functions. You can mark a socket as non-blocking with the fcntl() function as follows:

#include <fcntl.h>
...
int s;
...
s = socket(AF_INET, SOCK_STREAM, 0);
...
if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
    perror("fcntl(s, F_SETFL, O_NONBLOCK)");
    exit(1);
}
...

The fcntl() function is part of the basic scope of the POSIX interface. It is described in "fcntl() - control sockets" and in the manual "C Library Functions for POSIX Applications".

You should particularly watch out for the EWOULDBLOCK error when executing the accept(), connect() or input/output functions on non-blocking sockets. EWOULDBLOCK is stored in the global errno variable and occurs if a function which normally blocks is executed on a non-blocking socket.

The accept() and connect() functions as well as all read and write operations can return the EWOULDBLOCK error code. Processes should therefore be prepared to handle such return values.

There are situations in which, for example the send() function, can be executed only partially, i.e. only a part of the caller's data could be transferred immediately without getting blocked. Such situation is not indicated by EWOULDBLOCK but by the return value of the send() function which equals to the number of bytes transferred.