Today we are going to explore a very important system call in Linux, The Select system call. Select System call is use when we need non blocking executions. The use of the select can be explained via an example code. Lets assume that we use a socket program with a server and few client programs. To accept and read from clients what will be your normal approach?.. Probably you are checking for new clients and the data from the existing clients and probably use a read system call. Here the approach is blocking, the program is blocked for events. But using the select system call, it can be achieved in a non- blocking manner. Here we put the connected clients along with the server into a fd_set type variable. Then the select system call is looking for any read events for each clients and read the data non bloc-kingly.
Lets see an example code for this scenario.
In this example there is a server which is binded to port 9999. and clients can be connected to that port. Then the server identify whether a new client or data from an existing client. Select call will monitor the read_fds and act immediately for a change of a read file descriptor. There is a time out value for select system call.
In this example many clients are connected to the server and heart beats are send for the clients for every 3 seconds. And from the server we can send work(In this scenario messages) for clients. Then the clients work on those messages and send result to the server. We can non- bloc-kingly send data to clients and read data from clients using the select system call. :)
To compile and run the server...
To compile and run the client...
That's it folks. If you have anything to clarify just put a comment. I'll answer for the best of my knowledge.
Here is a nice tutorial for Linux system calls. I recommend you all to read it.