3

How to display open file descriptors with thread id without using lsof? I know a similar question exists but the answer doesn't include thread details.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

4

On top of the answers given, it is perhaps worth mentioning that in Linux, all threads started by a process, typically share the same set of file descriptors. Thus, both:

ls /proc/$parent_pid/task/$task/fd and ls /proc/$parent_process/fd

would typically produce the same output, which implies that child processes inherit the file descriptors referenced by their parent. The 'lsof' manual actually specifies that too under the -K option documentation:

"In general threads and tasks inherit the files of the caller, but may close some and open others, so lsof always reports all the open files of threads and tasks."

So to eliminate any potential ambiguity (perhaps created by the previous answers), listing /proc/$parent_pid/$task/fd does not guerantee that $task was the thread that refrences the file descriptor ids in that directory. If you need a reliable way of telling which thread opened a particular file descriptor, you can strace the program to track system calls like open(), that require the kernel to assign a file descriptor.

Uriah L.
  • 141
  • 1
    The assumption in this answer as well in the cited lsof man page seems to be in contradiction with this answer https://stackoverflow.com/a/1522077 which includes code-of-proof: "Threads share the same memory, so they share the same variables. If you close socket in parent thread, it will be also closed in child thread." According to https://unix.stackexchange.com/questions/364660/are-threads-implemented-as-processes-on-linux, Linux pthreads use Linux tasks via the clone() syscall with appropriate flags. – TheDiveO Jan 23 '20 at 16:06
  • I second that. I tried opening two threads from the main thread, t1 and t2. In the main thread I opened a file f1, in t2 a file f2 (different files). Browsing /proc/PID/task/*/fd shows both files open in all three threads (main, t1 and t2). – Dave Reikher Feb 18 '20 at 12:04
2

On Linux:

ls -l /proc/*/task/*/fd

Contrary to lsof, it only lists file descriptors, not mmapped files, root and current directories.

1

Well, you can inspect /proc/TID/fd.... I don't understand what's the issue here.

PersianGulf
  • 10,850