Select Rules!

Ok, I can honestly say that I never fully understood the usage of the C select() function until now. Well, let me rephrase - I understood how it works, that it can be used to wait until a given file descriptor is readable or writable (or has waiting OOB data, but who the hell cares about that).

Until now, I was kinda wondering why you would ever want to check if some files were ready to read or write. Then it hit me - BSD sockets are file descriptors.

int sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);

will create a file descriptor "sock" which will function exactly like a normal file descriptor. I'll save you the drudgery or actually binding the socket, and we'll just assume this is a server socket bound to a local address/port.

fd_set readable;
FD_ZERO(readable);
FD_SET(sock,readable);
int i = select(FD_SETSIZE,readable,0,0,0);

//a readable server socket indicats an incomming connection
if(FD_ISSET(sock,readable)) {
    int client = accept(sock,....sockaddr params go here...);
    /* Here we can add the "client" socket to the same fd_set If a client socket
     * ISSET, it indicates there is pending data to be read */
}

Using select to manage client sockets is an alternative to the typical fork()ing webserver - if you're interested, thttpd actually uses select().

Now that we've had our cake... let's eat it: Display* dpy = XOpenDisplay(0); if(dpy) { int x_fd = ConnectionNumber(dpy); FD_SET(x_fd,readable); int i = select(FD_SETSIZE,readable,0,0,0);

    if(FD_ISSET(sock,readable)) { /* handle socket data */
    if(FD_ISSET(x_fd,readable)) { /* handle new X11 events */ }
}

Yum.... cake

next

| | comments