如何从C++中获取Linux 2.6中的SPID

mik*_*ong 2 c++ linux multithreading pthreads

我有一个问题:从C++应用程序到linux 2.6中的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 -
Run Code Online (Sandbox Code Playgroud)

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

root@10.67.100.2:~# ls /proc/1120/task/
1120  1125  1126  1128  1129  1130  1131
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

/麦克风

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

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

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

我得到这个结果:

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

它们都不像ps或proc文件系统中给出的SPID.

另请注意,gettid不会返回SPID.

jpa*_*cek 6

如何gettid()

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

#include <sys/syscall.h>
syscall(SYS_gettid);
Run Code Online (Sandbox Code Playgroud)

...或参见本手册页上的示例.