Linux – How to get number of opened file descriptors for user

linuxnot-root-useropen filesusers

I know about lsof and ls /proc/*/fd but none of them are atomic AFAIK. Because in the latter case I would need to get all pids for user and then filter by them and by that time some of the file descriptors could be closed.

Maybe there is some system call for that or something, because obviously OS tracks that number as it would refuse to create FD if max limit for user is exhausted.

Best Answer

I haven't made an intensive search, but I don't think what you're looking for exists on Linux. Opening a file descriptor doesn't take any global lock, only a per-process lock, so on a multicore machine whatever you'd be using to count the number of open file descriptors could be running literally at the same time that other threads is opening or closing files on other cores.

Linux doesn't have a global limit on the total number of open files. There's no explicit per-user limit either. There's a per-user limit on processes, and a per-process limit on file descriptor numbers, which indirectly imposes a limit on open files per user, but that isn't explicitly tracked.

Exploring /proc (which is what lsof does under the hood) is as good as it gets. /proc is the Linux API to get information about processes.

Related Question