
假設我有一個程序,我想監視它的檔案系統活動(創建/修改/刪除了哪些檔案/目錄等)。如此。
我該怎麼做呢?
答案1
您可以使用strace
為了這:
strace -f -e trace=file command args...
strace
追蹤系統呼叫並在發生時將其描述列印到標準錯誤。該-f
選項告訴它也追蹤子進程和線程。-e
允許您修改它將追蹤的呼叫:將記錄、等-e trace=file
的每次使用,但不記錄非檔案操作。open
unlink
如果您想查看從文件中讀取的內容和寫入文件的內容,請將其變更為-e trace=file,read,write
;您也可以在那裡列出您想要檢查的任何其他呼叫。如果你完全放棄這個論點,你就會得到每個系統呼叫。
輸出如下(我mkdir /tmp/test
在追蹤的 shell 中運行):
[pid 1444] execve("/usr/bin/mkdir", ["mkdir", "/tmp/test4"], [/* 33 vars */]) = 0
[pid 1444] access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
[pid 1444] open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
[pid 1444] open("/usr/lib/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
[pid 1444] open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
[pid 1444] mkdir("/tmp/test", 0777) = 0
[pid 1444] +++ exited with 0 +++
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=1444, si_status=0, si_utime=0, si_stime=0} ---
您可以使用 登入檔案而不是終端-o filename
,並使用 -v 使輸出(甚至)更詳細。也可以使用 附加到已有的進程-p PID
,以防更有用。
如果您希望以程式設計方式執行此操作,而不是檢查自己,請查看ptrace
稱呼,這是strace
建構的基礎。