2

I know from this answer that pthread_t is struct pthread* on Linux. But I get the error:

a.c:35:60: error: invalid use of undefined type ‘struct pthread’
   35 |   printf("%ld: %ld\n", e, ((struct pthread*)(newthread))->tid); 

While in gdb I can do p ((struct pthread*)(newthread))->tid and it works well.

How can I do it in code?

JenyaKh
  • 2,040
  • 17
  • 25
  • 3
    It appears that `struct pthread` is not exposed to your code. The debugger may have information on it, but your code does not. I'm not sure what the purpose is here. If this is just for debugging something in your program, you could recreate the `struct` and cast to your version to get `tid`. Just be aware that doing so is not portable/robust and technically undefined behavior in C even though it will work. Again, it depends on the use case. You can always get thread id manually with `gettid`. – Jason Aug 28 '23 at 13:30
  • @Jason, I try to find a way to learn a tid of a thread created by pthread_create(). – JenyaKh Aug 28 '23 at 13:35
  • @Jason, this is for debugging purposes. I don't care about correctness, etc. – JenyaKh Aug 28 '23 at 13:37
  • 3
    The answer you are referring to states "`pthread_t` [...] is just the pointer to an *opaque* `struct pthread`". Opaque means you should not know the internal details of the structure. According to [POSIX](https://pubs.opengroup.org/onlinepubs/7908799/xsh/systypes.h.html), `pthread_t` could be an integral type instead of a pointer to a structure. Please explain in your question what you want to achieve with accessing this non-portable structure field. – Bodo Aug 28 '23 at 13:46

1 Answers1

0

I managed to get what I want in an ugly way, but that's enough for my purposes:

printf("%ld: %d\n", e, *((pid_t*)(((char*)newthread+720)))); 

I just explored it in gdb this way:

(gdb) p ((struct pthread*)handle)->tid
$1 = 3448

(gdb) p &(((struct pthread*)handle)->tid)
$2 = (pid_t *) 0x7fffd69ff910

(gdb) p ((struct pthread*)handle)
$3 = (pthread *) 0x7fffd69ff640

(gdb) p 0x7fffd69ff910 - 0x7fffd69ff640
$4 = 720

(gdb) p *((pid_t*)(((char*)handle)+720))
$5 = 3448
JenyaKh
  • 2,040
  • 17
  • 25
  • 1
    This is even more ugly and difficult to understand than using your own structure definition as proposed in [Jason](https://stackoverflow.com/users/635822/jason)'s [comment](https://stackoverflow.com/questions/76993170/print-tid-out-of-pthread-t-in-c-on-linux#comment135728801_76993170) – Bodo Aug 28 '23 at 14:10
  • Yeah, this is soooo much better than using [`gettid()`](https://man7.org/linux/man-pages/man2/gettid.2.html) as suggested in the very first comment to your question. – Andrew Henle Aug 28 '23 at 14:55
  • No, @AndrewHenle, gettid() does not suit here. It returns the tid of the _current_ thread. In my example _newthread_ is not the current thread. It is a thread created by _pthread_create()_ by the current thread. – JenyaKh Aug 28 '23 at 15:23