How to display open file descriptors with thread id without using lsof command

14,052

Solution 1

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.

Solution 2

On Linux:

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

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

Solution 3

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

Share:
14,052

Related videos on Youtube

Manoj Sharma
Author by

Manoj Sharma

Updated on September 18, 2022

Comments

  • Manoj Sharma
    Manoj Sharma over 1 year

    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.

  • TheDiveO
    TheDiveO over 4 years
    The assumption in this answer as well in the cited lsof man page seems to be in contradiction with this answer 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 unix.stackexchange.com/questions/364660/…, Linux pthreads use Linux tasks via the clone() syscall with appropriate flags.
  • Dave Reikher
    Dave Reikher about 4 years
    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).