在SMP系統中,我們的應用程序經常使用多線程的技術,那么在Linux中如何查看某個進程的多個線程呢?
本文介紹3種命令來查看Linux系統中的線程(LWP)的情況:
在我的系統中,用qemu-system-x86_64命令啟動了一個SMP的Guest,所以有幾個qemu的線程,以此為例來說明。
1. pstree 命令
查看進程和線程的樹形結構關系
查看源代碼
打印?·········10········20········30········40········50········60········
1.[root@jay-linux ~]# pstree | grep qemu
2. |-terminal-+-bash---qemu-sys---2*[{qemu-system-x8}]
3.[root@jay-linux ~]# pstree -p | grep qemu
4. |-terminal(194)-+-bash(196)---qemu-sys(657)-+-{qemu}(660)
5. | | `-{qemu}(661)
2. ps 命令
-L參數顯示進程,并盡量顯示其LWP(線程ID)和NLWP(線程的個數)。
查看源代碼
打印?·········10········20········30········40········50········60········
1.[root@jay-linux ~]# ps -eLf | grep qemu
2.root 657 196 657 0 3 13:48 pts/1 00:00:00 qemu-sys -m 1024 -smp 2
3.root 657 196 660 3 3 13:48 pts/1 00:00:26 qemu-sys -m 1024 -smp 2
4.root 657 196 661 2 3 13:48 pts/1 00:00:19 qemu-sys -m 1024 -smp 2
5.root 789 9799 10789 0 1 14:02 pts/0 00:00:00 grep --color=auto qemu
上面命令查詢結果的第二列為PID,第三列為PPID,第四列為LWP,第六列為NLWP。
另外,ps命令還可以查看線程在哪個CPU上運行,命令如下:
查看源代碼
打印?·········10········20········30········40········50········60········
1.[root@jay-linux ~]# ps -eo ruser,pid,ppid,lwp,psr,args -L | grep qemu
2.root 657 196 657 1 qemu-sys -hda smep-temp.qcow -m 1024 -smp 2
3.root 657 196 660 1 qemu-sys -hda smep-temp.qcow -m 1024 -smp 2
4.root 657 196 661 2 qemu-sys -hda smep-temp.qcow -m 1024 -smp 2
5.root 834 9799 10834 1 grep --color=auto qemu
其中,每一列依次為:用戶ID,進程ID,父進程ID,線程ID,運行該線程的CPU的序號,命令行參數(包括命令本身)。
3. top 命令
其中H命令可以顯示各個線程的情況。(在top命令后,按H鍵;或者top -H)
查看源代碼
打印?·········10········20········30········40········50········60········
01.[root@jay-linux ~]# top -H
02.top - 14:18:20 up 22:32, 4 users, load average: 2.00, 1.99, 1.90
03.Tasks: 286 total, 1 running, 285 sleeping, 0 stopped, 0 zombie
04.Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
05.Mem: 3943892k total, 1541540k used, 2402352k free, 164404k buffers
06.Swap: 4194300k total, 0k used, 4194300k free, 787768k cached
07.
08. PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
09.660 root 20 0 1313m 188m 2752 S 2.3 4.9 0:46.78 qemu-sys
10.661 root 20 0 1313m 188m 2752 S 2.0 4.9 0:39.44 qemu-sys
11.867 root 20 0 15260 1312 960 R 0.3 0.0 0:00.07 top
12. 1 root 20 0 19444 1560 1252 S 0.0 0.0 0:00.34 init
13. 2 root 20 0 0 0 0 S 0.0 0.0 0:00.02 kthreadd
14.....
在top中也可以查看進程(進程)在哪個CPU上執行的。
執行top后,按f,按j(選中* J: P = Last used cpu (SMP)),然后按空格或回車退出設置,在top的顯示中會多出P這一列是最近一次運行該線程(進程)的CPU.
原文轉自:http://linux.cn/thread/11492/1/1/