我有一个函数,可以从IRC服务器接收512字节块的数据,并将其打印到终端窗口,它是这样的:
int mainLoop(redchan_t *redchan)
{
int socketDescriptor = redchan->socketDescriptor, i, bytesReceived;
char workingBuffer[RECVBUFF] = {[0 ... RECVBUFF - 2] = '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;
}
但我想让它更正交,所以我打电话给recv,并把它放在自己的程序中,看起来像这样:
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;
}
然后,我只需要在主循环的每次迭代中调用redchanRecv(),然后打印缓冲区。但当我运行它时,它几乎打印出所有内容,只有一行除外。最后一行永远不会到达终端(它甚至会进入缓冲区吗?)。我真的觉得我犯了一个新手的错误,但如果我能看到的话,那就见鬼去吧。我该如何解决这个问题?
stdout
在系统中默认为行缓冲,添加一个fflush(stdout)
调用以打印最后一行。