【发布时间】:2012-06-24 16:16:29
【问题描述】:
我有一个 jabber 服务器应用程序和另一个 C++ 中的 jabber 客户端应用程序。
当客户端接收和发送大量消息(每秒超过 20 条)时,选择就会冻结,永远不会返回。
使用 netstat,socket 仍然在 linux 上连接,使用 tcpdump,消息仍然发送到客户端,但 select 永远不会返回。
这里是选择的代码:
bool ConnectionTCPBase::dataAvailable( int timeout )
{
if( m_socket < 0 )
return true; // let recv() catch the closed fd
fd_set fds;
struct timeval tv;
FD_ZERO( &fds );
// the following causes a C4127 warning in VC++ Express 2008 and possibly other versions.
// however, the reason for the warning can't be fixed in gloox.
FD_SET( m_socket, &fds );
tv.tv_sec = timeout / 1000000;
tv.tv_usec = timeout % 1000000;
return ( ( select( m_socket + 1, &fds, 0, 0, timeout == -1 ? 0 : &tv ) > 0 )
&& FD_ISSET( m_socket, &fds ) != 0 );
}
而死锁是gdb:
Thread 2 (Thread 0x7fe226ac2700 (LWP 10774)):
#0 0x00007fe224711ff3 in select () at ../sysdeps/unix/syscall-template.S:82
#1 0x00000000004706a9 in gloox::ConnectionTCPBase::dataAvailable (this=0xcaeb60, timeout=<value optimized out>) at connectiontcpbase.cpp:103
#2 0x000000000046c4cb in gloox::ConnectionTCPClient::recv (this=0xcaeb60, timeout=10) at connectiontcpclient.cpp:131
#3 0x0000000000471476 in gloox::ConnectionTLS::recv (this=0xd1a950, timeout=648813712) at connectiontls.cpp:89
#4 0x00000000004324cc in glooxd::C2S::recv (this=0xc5d120, timeout=10) at c2s.cpp:124
#5 0x0000000000435ced in glooxd::C2S::run (this=0xc5d120) at c2s.cpp:75
#6 0x000000000042d789 in CNetwork::run (this=0xc56df0) at src/Network.cpp:343
#7 0x000000000043115f in threading::ThreadManager::threadWorker (data=0xc56e10) at src/ThreadManager.cpp:15
#8 0x00007fe2249bc9ca in start_thread (arg=<value optimized out>) at pthread_create.c:300
#9 0x00007fe22471970d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:112
#10 0x0000000000000000 in ?? ()
您知道什么会导致 select 停止接收消息,即使我们仍在向他发送消息。 通过socket接收和发送大量消息时,linux中是否有缓冲区限制?
谢谢
【问题讨论】:
-
可能对方崩溃或关闭。我建议始终对
select设置非无限超时(例如一秒超时)。我还建议使用poll而不是select。你可以strace你的程序来找出select是如何“错误地”表现出来的。 -
另一端(服务器)仍在运行,仍在发送消息。使用 tcpdump,我可以看到发送到客户端端口的那些消息。我们不在 select 中使用 timeout 的原因是不要在没有发送任何内容的时候过度消耗 cpu。此外,当我在客户端上运行 strace 时,他仍在套接字上等待。并且套接字在 /proc/
/fd/ 中仍然可用 -
"使用 tcpdump,我可以看到发送到客户端端口的那些消息"。那么你在服务器端运行 tcpdump 吗?如果你在本地机器上嗅探流量怎么办?那些数据包到达了吗?
-
您至少可以检查 select() 的返回值,如果是 -1,请检查 errno。可以是 EINTR / EAGAIN 或 EINVAL ... 或任何东西。
-
服务器和客户端在同一台机器上运行。所以客户端连接到服务器到端口5222,客户端端口就像41919。所以当我在接口'lo'上运行tcpdump时,我可以看到一个数据包已经从5222传递到端口41919
标签: c++ linux select deadlock gloox