在接收整数数组时,需要检查所接收的数据的字节。 例如,当接收长度为100的整数数组时:
int count = 0;
int msg[100];
while(count < 100 * sizeof(int)){
count += read(fd, msg + count / sizeof(int), 100 * sizeof(int) - count);
}
这是正确的方法吗?read()函数返回的值是否可能不是int类型的倍数? 如果这种方法不正确,那么接收整数数组的正确方法是什么?
read()
也可能返回-1,这在OP的源代码中没有考虑到,因此后一种情况会完全破坏算法。另外,read()
返回0
的情况,即另一端关闭了连接,也没有被考虑在内,会导致无限循环。 - alk