問題描述
Android文件描述符洩漏調試 (Android file descriptor leakage debuging)
我們公司有很多在虛擬/真實設備上運行的 ui 測試。運行一段時間後測試隨機崩潰,我認為這是文件描述符超出的結果:我使用了
ls /proc/${PID}/fd | wc ‑l
和 lsof ‑p ${PID}
但它並沒有太大幫助 ‑ lsof 中的大多數行看起來像:
30015 u0_a104 678 sock 859560 socket:[859560]
30015 u0_a104 679 0000 0,8 4539 anon_inode:[eventpoll]
30015 u0_a104 680 0000 0,8 4539 anon_inode:[eventfd]
30015 u0_a104 681 0000 0,8 4539 anon_inode:[eventfd]
30015 u0_a104 682 0000 0,8 4539 anon_inode:[eventpoll]
30015 u0_a104 683 0000 0,8 4539 anon_inode:[eventfd]
30015 u0_a104 684 0000 0,8 4539 anon_inode:[eventpoll]
30015 u0_a104 685 0000 0,8 4539 anon_inode:[eventfd]
所以我的問題是:是否有任何 android/java/linux 工具/工具可以找到洩漏的來源?
PS System.gc() 沒有幫助
參考解法
方法 1:
I have researched for this question for a while and would like to share what I found:
File descriptor are used in Android at least for:
- Network sockets (or another type of file)
- Mapped to memory files
- Threads ‑ so it was my case. See below why
If you have created a HandlerThread, even if the last link to the HandlerThread instance will disappear thread will still work and consume FileDescriptor
Threads in android can be seen:
- In "Java heap dump" in Memory Abalyze Tool ‑ so I have seen > 500 threads while running intsrumentation tests ‑ they "eat" all file descriptors
- Via terminal on android device
adb shell ps ‑t
or justps ‑t