how to find per-user disk-space-usage?

Issue

I am writing a small tool in which I require to find per-user File-system-memory-usage.

I have to do some clean up activity if file-system usage is crossing certain threshold value. What is the system call that I can use, so that I could be able to find per user memory usage?

Solution

Maybe you are interested in disk quotas (which are supported by some, but not all, filesystems). The low-level system call is quotactl(2). Perhaps using the existing tools quota(1) and quotacheck, edquota, warnquota, quotaon etc…. might be enough.

If you want to know the memory used by a given process, consider the getrusage(2) syscall. You can also read pseudo-files under /proc/self/ or /proc/1234 for pid 1234. You can also scan the /proc/ (using usual directory scanning routines: opendir(3), looping on readdir(3) with stat(2), closing with closedir…) for numerical directories (since /proc/1234/ describes the process of pid 1234). Read more about proc(5) (e.g. /proc/self/maps or /proc/1234/smaps and /proc/1234/status etc). Tou can query the virtual address space of process 1234 by reading the /proc/1234/status and /proc/1234/maps pseudo-files. Try for example cat /proc/$$/status and cat /proc/$$/maps in a terminal to query info for your current shell process.

Of course, consider also the du(1) and df(1) commands (perhaps invoke them carefully thru popen(3) if you want to get their output). If for whatever reasons you want to recursively scan a file tree (e.g. to count its cumulated used size like du does), consider using the nftw(3) functions. See also stat(2) and statfs(2) syscalls.

Remember that other processes can (and often do) write to the filesystem while your program is exploring or querying it. And your user could start new processes (perhaps indirectly, e.g. with crontab(5), system(3), fork(2) and execve(2), at, batch, ssh …) at any time.

Read also a good Linux programming book, perhaps the old Advanced Linux Programming, and syscalls(2)

I am writing a small tool in which I require to find per-user File-system-memory-usage.

If you are coding in C on Linux, consider using your clever mix of nftw(3) and stat(2) and statfs(2).

Answered By – Basile Starynkevitch

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published