2016-01-30 20 views
3

我有一台用C++编写的服务器,它在osx上运行时会泄露Mach端口。具体来说,在运行top时,我注意到它有大约50000(在#PORTS下)。奇怪的是,我让它在一夜之间运行,第二天机器基本上已经死机(花了15分钟响应ctrl-c,没有接受新的ssh连接),所以IT不得不重新启动它。这样的泄漏是否会导致系统崩溃?它没有以root身份运行。我应该如何去调试Mach端口泄漏?

无论如何,有什么好的策略来寻找这种泄漏的原因?有没有好的工具?

我发现一个测试,当运行可靠泄漏5端口,但就是这样。

编辑:我发现我们的线程类创建了一个mach端口泄漏,但我不明白为什么。在构造函数中,我们有下面的代码:

// Initialize the default attributes. 
if (0 != pthread_attr_init(&m_threadAttributes)) 
{ 
    throw "blah"; 
} 

// Set the thread to be joinable. 
if (0 != pthread_attr_setdetachstate(&m_threadAttributes, PTHREAD_CREATE_JOINABLE)) 
{ 
    pthread_attr_destroy(&m_threadAttributes); 
    throw "blah"; 
} 

if (0 != pthread_create(
      &m_thread, 
      &m_threadAttributes, 
      &StartThreadFunction, 
      reinterpret_cast<void*>(this))) 
{ 
    throw "blah"; 
} 

而且我注意到端口数为进程调用pthread_create,预计后上升的一个。

然后,后来我加入用下面的代码线程:

if (0 != pthread_join(m_thread, NULL)) 
{ 
    throw "blah"; 
} 

而且不会抛出异常,所以我只能假设pthread_join返回0,因此成功,但在顶部没有按端口#不要下去。还有什么我需要做清理线程?

回答

2

您可以使用Dtrace来检测正在运行的系统上的马赫数端口使用情况。有许多mach_port相关的探测器:

sudo dtrace -l | grep mach_port

你可以写一个DTrace脚本,跟踪每个阉每个端口创建或保留的呼叫由相应的释放平衡。跟踪内存泄漏的Dtrace脚本将是一个有用的起点。

一旦你有一个为你的目的工作的脚本you can use Instruments to control the trace session and graph the results

+0

是的,我早些时候试过dtrace,它可能是一个痛苦,获得对本机的root权限...... – Bwmat