I'm writing a simple IRC client program in C for self-teaching purposes, and am having trouble understanding the behavior of the read()
function when called reading from a socket file descriptor.
The following code snippet works and prints the same output as running
$ echo "NICK gertrudes\r\nUSER a 0 * d\r\n" | nc chat.freenode.net 6667
in the terminal, which is the same as my program prints so far:
while ((n = read(sockfd, buffer, sizeof(buffer)-1)) > 0) {
printf("\nloop\n");
buffer[n] = '\0';
if (fputs(buffer, stdout) == EOF)
error("fputs");
}
if (n < 0)
error("reading from socket");
printf("out of the loop\n");
What I fail to understand is why the program never gets to the final printf
call, and rather sits there as if waiting for more from the server. Does that mean that the last reply was longer than 0 and the IRC server just won't send anything new until I send another command?
If so (at the risk of going off-topic here), and read()
is blocking, where would I write the logic of sending commands to the server while the program is waiting for that call to return?