【问题标题】:How to get the SPID in linux 2.6 from C++如何从 C++ 获取 linux 2.6 中的 SPID
【发布时间】:2009-03-31 07:36:51
【问题描述】:

我有一个问题:在 linux 2.6 中是否可以通过 C++ 应用程序访问 SPID?当我执行“ps -amT”时,我可以看到进程中的线程:

root@10.67.100.2:~# ps -amT
  PID  SPID TTY          TIME CMD
 1120     - pts/1    00:00:20 sncmdd
    -  1120 -        00:00:00 -
    -  1125 -        00:00:00 -
    -  1126 -        00:00:00 -
    -  1128 -        00:00:00 -
    -  1129 -        00:00:09 -
    -  1130 -        00:00:00 -
    -  1131 -        00:00:09 -
 1122     - pts/1    00:00:00 snstatusdemuxd
    -  1122 -        00:00:00 -
    -  1127 -        00:00:00 -
    -  1132 -        00:00:00 -
    -  1133 -        00:00:00 -

然后在文件系统中我可以看到线程:

root@10.67.100.2:~# ls /proc/1120/task/
1120  1125  1126  1128  1129  1130  1131

那么有什么方法可以让我从我的应用程序中获取 SPID,以便我能以某种方式识别每个正在运行的线程中我的 SPID 是什么?

谢谢!

/迈克

编辑:我应该补充一点,从 getpid() 返回的 PID 在每个线程中都是相同的。

当我将此代码添加到我的线程时:

// Log thread information to syslog
syslog(LOG_NOTICE, "ibnhwsuperv: gettid()= %ld,  pthread_self()=%ld", (long int)syscall(224), pthread_self());

我得到这个结果:

Jan  1 01:24:13 10 ibnhwsupervd[1303]: ibnhwsuperv: gettid()= -1,  pthread_self()=839027488

两者都不像 ps 或 proc 文件系统中给出的 SPID。

另外,请注意gettid does not return the SPID

【问题讨论】:

  • 链接在哪里说 gettid 不返回 SPID?从你得到一个错误(它返回-1)的事实来看,我认为你只是把系统调用号弄错了。 224 仅适用于某些架构。
  • 返回 -1 可能意味着系统调用有错误。看看errno。你确定你说的对吗?使用 syscall() 听起来是错误的。无论如何,请使用名称 (SYS_gettid) 而不是数字。 syscall(SYS_gettid) 对我有用。

标签: c++ linux multithreading pthreads


【解决方案1】:

gettid()怎么样?

编辑:如果你的 libc 没有 gettid() 函数,你应该像这样运行它:

#include <sys/syscall.h>
syscall(SYS_gettid);

...或查看example on this manual page

【讨论】:

  • 感谢您的回复。参考文献最新编辑,gettid 调用不返回 SPID。
猜你喜欢
  • 1970-01-01
  • 2018-06-25
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
相关资源
最近更新 更多