7

I am working in glibc and I need to get the id of the current thread. For this i use syscall(SYS_gettid); Issue is, i am forced to include bits/syscall.h instead of ideal case i.e sys/syscall.h.

sys/syscall.h internally calls bits/syscall.h but that is wrapped with #ifndef _LIBC macro. i.e

     #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

also bits/syscall.h states that "Never use bits/syscall.h directly; include sys/syscall.h instead."

Since _LIBC will be defined in my case as i am writing code directly in malloc.c, please suggest my how can i overcome this.

Thanks, Kapil

osgx
  • 90,338
  • 53
  • 357
  • 513
Kapil
  • 836
  • 2
  • 8
  • 20

1 Answers1

20

gettid() is a system call. As for as I know there is no glibc wrapper for gettid. You need to invoke gettid() using syscall(). The following code works for me.

#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;
}
  • 1
    this is fine. It will work, no issues. The similar code will not work if written iside glibc. and you will get and undefined reference error to SYS_gettid and that will be due to the fact that bits/syscall.h will not be included as _LIBC is true in that case. I hope you understood now. – Kapil Mar 14 '12 at 07:52
  • 1
    This is not really an answer because OP knows how to use `syscall()` or `gettid()`. The question was how to do it inside glibc library. Not to mention that your code sample was not legal C98 and was missing necessary includes. –  Aug 10 '13 at 15:39
  • 2
    (Many years later) It looks like [glibc 2.30 finally added `gettid()`](https://sourceware.org/git/?p=glibc.git;a=commit;h=1d0fc213824eaa2a8f8c4385daaa698ee8fb7c92)for Linux so if know you're using a version equal to or above that you won't need to do it as a syscall ([glibc 2.30 was released on 1st August 2019](https://sourceware.org/git/?p=glibc.git;a=tag;h=refs/tags/glibc-2.30))... – Anon Sep 18 '19 at 05:16