测试程序如下:
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void * thread_start(void *arg)
{
printf("Process ID: %d, thread ID %d\n", getpid(), gettid());
}
int main(void)
{
pthread_t tid;
pthread_attr_t attr;
void *status = NULL;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 256 * 1024);
pthread_create(&tid, &attr, &thread_start, NULL);
pthread_attr_destroy(&attr);
pthread_join(tid, &status);
return 0;
}
编译的时候报错:
error: ‘gettid’ was not declared in this scope
printf("Process ID: %d, thread ID %d\n", getpid(), gettid());
man gettid:
#include <sys/types.h>
pid_t gettid(void);
Note: There is no glibc wrapper for this system call; see NOTES.
NOTES
Glibc does not provide a wrapper for this system call; call it using syscall(2).
原来 glibc 并没有提供这个接口。。
修改程序如下:
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <unistd.h>
void * thread_start(void *arg)
{
printf("[1] Process ID: %d, thread ID %d\n", getpid(), syscall(__NR_gettid));
printf("[2] Process ID: %d, thread ID %d\n", getpid(), syscall(SYS_gettid));
}
输出如下:
[1] Process ID: 12585, thread ID 12586
[2] Process ID: 12585, thread ID 12586
P.S.
在文件 /usr/include/bits/syscall.h里, 有一行:
#define SYS_gettid __NR_gettid
__NR_gettid是系统调用号。