用glibc打电话给gettid

Kap*_*pil 6 malloc glibc libc system-calls linux-kernel

我在glibc工作,我需要得到当前线程的id.为此我使用 syscall(SYS_gettid);问题是,我被迫包括bits/syscall.h而不是理想的情况即 sys/syscall.h.

sys/syscall.h 内部调用bits/syscall.h但是用#ifndef _LIBC宏包装.即

     #ifndef _LIBC
        /* The Linux kernel header file defines macros `__NR_<name>', but some
           programs expect the traditional form `SYS_<name>'.  So in building libc
           we scan the kernel's list and produce <bits/syscall.h> with macros for
           all the `SYS_' names.  */
       # include <bits/syscall.h>
    #endif
Run Code Online (Sandbox Code Playgroud)

bits/syscall.h指出"永远不要直接使用bits/syscall.h;而是包含sys/syscall.h".

由于_LIBC我将在我的情况下定义,因为我正在直接编写代码malloc.c,请建议我如何克服这个问题.

谢谢,卡皮尔

小智 16

gettid()是一个系统调用.至于我知道gettid没有glibc包装器.您需要使用syscall()调用gettid().以下代码适用于我.

#include <sys/syscall.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    long tid;

    tid = syscall(SYS_gettid);
    printf("%ld\n", tid);
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

  • (很多年后)看起来像[glibc 2.30终于为Linux添加了 `gettid()`](https://sourceware.org/git/?p=glibc.git;a=commit;h=1d0fc213824eaa2a8f8c4385daaa698ee8fb7c92),所以如果知道的话您使用的版本等于或高于您不需要将其作为系统调用的版本([glibc 2.30 于 2019 年 8 月 1 日发布](https://sourceware.org/git/?p=glibc.git ;a=标签;h=refs/tags/glibc-2.30))... (2认同)