Linux中查看進程的多線程
在SMP系統(tǒng)中,我們的應(yīng)用程序經(jīng)常使用多線程的技術(shù),那么在Linux中如何查看某個進程的多個線程呢?
本文介紹3種命令來查看Linux系統(tǒng)中的線程(LWP)的情況:
在我的系統(tǒng)中,用qemu-system-x86_64命令啟動了一個SMP的Guest,所以有幾個qemu的線程,以此為例來說明。
1. pstree 命令
查看進程和線程的樹形結(jié)構(gòu)關(guān)系
- [root@jay-linux ~]# pstree | grep qemu
- |-terminal-+-bash---qemu-sys---2*[{qemu-system-x8}]
- [root@jay-linux ~]# pstree -p | grep qemu
- |-terminal(194)-+-bash(196)---qemu-sys(657)-+-{qemu}(660)
- | | `-{qemu}(661)
2. ps 命令
-L參數(shù)顯示進程,并盡量顯示其LWP(線程ID)和NLWP(線程的個數(shù))。
- [root@jay-linux ~]# ps -eLf | grep qemu
- root 657 196 657 0 3 13:48 pts/1 00:00:00 qemu-sys -m 1024 -smp 2
- root 657 196 660 3 3 13:48 pts/1 00:00:26 qemu-sys -m 1024 -smp 2
- root 657 196 661 2 3 13:48 pts/1 00:00:19 qemu-sys -m 1024 -smp 2
- root 789 9799 10789 0 1 14:02 pts/0 00:00:00 grep --color=auto qemu
上面命令查詢結(jié)果的第二列為PID,第三列為PPID,第四列為LWP,第六列為NLWP。
另外,ps命令還可以查看線程在哪個CPU上運行,命令如下:
- [root@jay-linux ~]# ps -eo ruser,pid,ppid,lwp,psr,args -L | grep qemu
- root 657 196 657 1 qemu-sys -hda smep-temp.qcow -m 1024 -smp 2
- root 657 196 660 1 qemu-sys -hda smep-temp.qcow -m 1024 -smp 2
- root 657 196 661 2 qemu-sys -hda smep-temp.qcow -m 1024 -smp 2
- root 834 9799 10834 1 grep --color=auto qemu
其中,每一列依次為:用戶ID,進程ID,父進程ID,線程ID,運行該線程的CPU的序號,命令行參數(shù)(包括命令本身)。
3. top 命令
其中H命令可以顯示各個線程的情況。(在top命令后,按H鍵;或者top -H)
- [root@jay-linux ~]# top -H
- top - 14:18:20 up 22:32, 4 users, load average: 2.00, 1.99, 1.90
- Tasks: 286 total, 1 running, 285 sleeping, 0 stopped, 0 zombie
- 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
- Mem: 3943892k total, 1541540k used, 2402352k free, 164404k buffers
- Swap: 4194300k total, 0k used, 4194300k free, 787768k cached
- PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
- 660 root 20 0 1313m 188m 2752 S 2.3 4.9 0:46.78 qemu-sys
- 661 root 20 0 1313m 188m 2752 S 2.0 4.9 0:39.44 qemu-sys
- 867 root 20 0 15260 1312 960 R 0.3 0.0 0:00.07 top
- 1 root 20 0 19444 1560 1252 S 0.0 0.0 0:00.34 init
- 2 root 20 0 0 0 0 S 0.0 0.0 0:00.02 kthreadd
- ....
在top中也可以查看進程(進程)在哪個CPU上執(zhí)行的。
執(zhí)行top后,按f,按j(選中* J: P = Last used cpu (SMP)),然后按空格或回車退出設(shè)置,在top的顯示中會多出P這一列是最近一次運行該線程(進程)的CPU。
- PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ P COMMAND
- 661 root 20 0 1313m 188m 2752 S 2.3 4.9 0:44.24 3 qemu-sys
- 660 root 20 0 1313m 188m 2752 S 2.0 4.9 0:51.74 0 qemu-sys
- 874 root 20 0 15260 1284 860 R 0.7 0.0 0:00.32 2 top
- 1 root 20 0 19444 1560 1252 S 0.0 0.0 0:00.34 0 init
- 2 root 20 0 0 0 0 S 0.0 0.0 0:00.02 1 kthreadd
更多信息,請 man pstree, man top, man ps 查看幫助文檔。
注: LWP為輕量級進程(即:線程),(light weight process, or thread) 。