Search code examples
clinuxptrace

calculate the amount of memory used by a particular process in linux


I'm writing a program to trace every system call called by child process and determine the exact memory use of it(excluding sharing memory).

here's my plan.

let child process ptraced by father process,

if child process make system calls, father process will recieve SIGTRAP,

then get syscall id with ptrace(PTRACE_PEEKUSER, child_pid, 4*ORIG_EAX, NULL).

when the id equals to SYS_brk, SYS_sbrk, SYS_mmap2, SYS_mmap, SYS_mremap, SYS_munmap ,

i am able to get parameters of the call and calculate the amount of memory use.

but it troubles me that

  1. I'm not sure how to calculate.

  2. SYS_mmap2 has over 6 parameters, how should I get it?


Solution

  • To determine the memory use for a process of pid 1234, I suggest reading sequentially and parsing the /proc/1234/maps or /proc/1234/smaps pseudo-file. Other files under /proc/1234/ could be also relevant (e.g. /proc/1234/statm and /proc/1234/status)

    From inside a process, you can read /proc/self/maps or /proc/self/smaps (and e.g. /proc/self/statm and /proc/self/status).

    Read the proc(5) man page for details.

    There is also the pmap command