clinuxwebsocketircberkeley-sockets

IRC program not printing last message


I had a function that would receive data from an IRC server in 512-byte chunks and print it to the terminal window, it went like this:

int mainLoop(redchan_t *redchan)
{
    int socketDescriptor = redchan->socketDescriptor, i, bytesReceived;
    char workingBuffer[RECVBUFF] = {[0 ... RECVBUFF - 2] = '0', '\0'};

    puts("Recieving data...");

    do
    {
        if ((bytesReceived = recv(
                socketDescriptor,
                workingBuffer,
                RECVBUFF,
                0)) == 0)
            exit(EXIT_FAILURE);

        for (i = 0; i < bytesReceived; ++i)
            printf("%c", workingBuffer[i]);
    }
    while(1);

    return 0;
}

But I wanted to make it more orthogonal so I took out the call to recv and put it in its own routine which looks like this:

int redchanRecv(redchan_t *redchan, int size, char *buffer)
{
    int totalBytes = 0, bytesReceived;

    while (totalBytes < size)
    {
        if ((bytesReceived = recv(
                        redchan->socketDescriptor,
                        buffer + totalBytes,
                        size - totalBytes,
                        0)) <= 0)
            cleanup_redchan(redchan, serverInfo);
        totalBytes += bytesReceived;
    }
    return 0;
}

I would then just call redchanRecv() in each iteration of my main loop and then print the buffer. But when I run it, it prints out almost everything, except for one line. That last line never makes it to the terminal (does it even make it into the buffer?). I really feel like I'm making a rookie mistake but hell if I can see it. How can I solve this?


Solution

  • stdout is line-buffered by default in your system, add a fflush(stdout) call to have your last line printed.