问题
I need to get some statistic(io, network) of a process during its lifetime. Is there anyway to get those information from /proc just before the process exit ? Linux Kernel API ?
回答1:
wait4()
and struct rusage
A simple way to gather some statistics after child process termination is wait4(2) syscall, which can fill rusage struct.
ptrace()
If it's not enough, you can probably use ptrace(2) to stop a process just before its termination:
PTRACE_O_TRACEEXIT (since Linux 2.5.60)
Stop the tracee at exit. A
waitpid(2)
by the tracer will return a status value such thatstatus>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))
The tracee's exit status can be retrieved with
PTRACE_GETEVENTMSG
.The tracee is stopped early during process exit, when registers are still available, allowing the tracer to see where the exit occurred, whereas the normal exit notification is done after the process is finished exiting. Even though context is available, the tracer cannot prevent the exit from happening at this point.
When waitpid(2) will report that process is going to terminate and stopped, you can gather statistics from /proc
, but I didn't try this.
KProbes
The most generic solution I know is KProbes and derivatives. You can probably use DTrace or SystemTap to trap sys_exit()
and gather statistics.
来源:https://stackoverflow.com/questions/34763987/extract-all-statistic-of-a-process-from-proc-just-before-the-process-exit-linu