在linux下开发的多线程系统中,每个线程的调试和监控一直比较麻烦,无法精准定位,现在有了解决办法了。
linux下的prctl库自kernel 2.6.9后支持
PR_SET_NAME选项,用于设置进程名字
,linux的进程一般使用lwp,所以这个函数可以设置线程名字。
api定义如下
int prctl( int option,unsigned long arg2,unsigned long arg3,unsigned long arg4,unsigned long arg5);
PR_SET_NAME (since Linux 2.6.9)
Set the process name for the calling process, using the value in the location pointed to by (char *) arg2. The name can be up to 16 bytes long, and should be null-terminated if it contains fewer bytes.
PR_GET_NAME (since Linux 2.6.11)
Return the process name for the calling process, in the buffer pointed to by (char *) arg2. The buffer should allow space for up to 16 bytes; the returned string will be null-terminated if it is shorter than that.
简单实现代码:
int set_thread_title(const char* fmt, )
{
char title [16] ={0};
va_list ap;
va_start(ap, fmt);
vsnprintf (title, sizeof (title) , fmt, ap);
va_end (ap);
return prctl(PR_SET_NAME,title) ;
}
现在能够为线程设置名字了,那么如何看到呢
ps -eL -o pid,user,lwp,comm
top -H