我已经实现了如下所示的套接字通信:
套接字客户端发送“0010ABCDEFGHIJ”到套接字服务器, 前 4 个字节(在本例中为“0010”)描述消息正文有 10 个字节, 后面的字节是消息正文!!
我在服务器端使用“Linux编程接口(interface)”readn函数, 来源:
ssize_t
readnx(int fd, void *buffer, size_t n)
{
ssize_t numRead; /* # of bytes fetched by last read() */
size_t totRead; /* Total # of bytes read so far */
char *buf;
buf = (char*) buffer; /* No pointer arithmetic on "void *" */
for (totRead = 0; totRead < n; ) {
numRead = recv(fd, buf, n - totRead,MSG_NOSIGNAL);
if (numRead == 0) /* EOF */
return totRead; /* May be 0 if this is first read() */
if (numRead == -1) {
if (errno == EINTR)
continue; /* Interrupted --> restart read() */
else
return -1; /* Some other error */
}
totRead += numRead;
buf += numRead;
}
return totRead; /* Must be 'n' bytes if we get here */
}
void *thread1(void *param)
{
int nread = 0 ;
char strdata[1024]={0},strtmp[128]={0} ;
pthread_detach(pthread_self());
while(1)
{
memset(strtmp,0x00,sizeof(strtmp)) ;
if ( (nread = readnx(sd,strtmp,4)) <= 0){
break ;
}
int ilen = atoi(strtmp) ;
memset( strdata,0x00,sizeof(strdata) ) ;
if ( (nread = readnx(sd,strdata,ilen)) <= 0){
break ;
}
}//while
}
这对我来说效果很好,我想了解有关性能的更多细节, 我的源代码中有 2 个 readnx 函数调用,并在 阻塞模式,如果我更改代码以首先使用 MSG_PEEK 进行接收, 一旦所有 14 个字节都可用,然后调用 readnx 一次来获取所有数据, 它会比我原来的 2 个 readnx 调用更快吗?!
我想知道在我的原始来源中,我有 2 个 readnx 来接收“0010” 和“ABCDEFGHIJ”分别,这会导致linux内核复制到 用户空间两倍,即使所有 14 个字节都已经存在了 首先调用 readnx ?!或者内核将所有14个字节复制到用户空间 只需一次,readnx 函数就从用户空间读取它?!
如果我想了解有关内核到用户空间过程的详细信息, 什么文档、函数调用可以帮助我了解详细信息。
最佳答案
If I change my code to make recv with MSG_PEEK first, once all 14 bytes are all available
这意味着您要 sleep 并重试。你要睡多久?你怎么知道这些碎片到达的时间相隔多远?
then call readnx once to fetch all datas, Would it be faster than my original 2 readnx calls?
没有。与 recv()
不同,您不会休眠正确的时间,并且您可能会执行多次 MSG_PEEK 接收操作。
如果您担心两个 recv()
调用的性能,或者无论调用多少次,您都应该在发送方处尽力确保 header 和消息同时发送:查看 sendmsg()
。
关于c - c中recv的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439240/