0

I have a process with 100 threads.

I know that only one thread is using a specific fd.

For example, this fd is a socket descriptor, and only one thread is using this socket with send() and receive().

How can I find out, with C, on Linux, the ID of this thread?

Is there a smarter way than attaching to each thread with ptrace and waiting until one of them will be detected?

Alfie
  • 2,341
  • 2
  • 28
  • 45
Keystone
  • 165
  • 1
  • 9

1 Answers1

2

File descriptors are part of the process. And since a file descriptor is just a nonnegative integer, and can be used by all threads of the same processes without explicit rebinding, asking "which thread holds an fd" is not a question applicable to the Linux process/threading model.

If you really want an answer then it would be: All the threads do!

datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • I understand you, but in the process I talk about,only 1 thread use this fd. The rest of threads can use, but they don't, so I want to find out this thread id – Keystone Jan 17 '20 at 10:56
  • 1
    @Keystone Well then you have to wait until one of the threads decides to use it, which you can do with `ptrace`, like you said. – user253751 Jan 17 '20 at 11:12
  • @Keystone: Yes, I fully understood your question. But a solution of the specific shape you're looking for does not exist. File descriptors are just numbers (and usually very small ones for that), so any (thread local) stack location where a number equal to one of the opened file descriptors resides, *could* be indicative of that peculiar thread making use of the file descriptor. Or not, because it could be just happenstance. The only dead sure indication for a particular thread using a particular file descriptor is, when it actually does a syscall on the file descriptor in question. → ptrace – datenwolf Jan 17 '20 at 16:25
  • 1
    @Keystone, In other words,... You _can't_ get that information from the OS. The OS does not care which thread opened a file, the OS does not keep any record of which thread opened the file, and the OS doesn't care which thread uses the file. The only way you could possibly find out the answer is if _your own code_ makes the information available. (E.g., every time your program opens a file, have it write a message to a log file containing the identity of the file and the identity of the thread that opened it.) – Solomon Slow Jan 17 '20 at 16:30