linux 之 taskset 绑核

发布时间 2023-07-31 14:25:44作者: 牛博张
1. 什么是 taskset?
    taskset命令用于设置进程(或线程)的 cpu 绑定情况(Processor Affinity),可以将进程(或线程)绑定到特定的一个或多个CPU上去执行,而不允许将进程(或 线程)调度到其他的CPU上。

2. 使用场景
     2.1 查看具体某一进程(或线程)的 cpu 绑定情况:使用参数 -p , 例如查看 qemu-kvm 进程绑定在哪个核上:ps -elf | grep qemu-kvm
     root@localhost ~]# ps -eLf | grep qemu
     root       1389   1339   1389  0    3 14:48 pts/0    00:00:10 /usr/libexec/qemu-kvm -cpu SandyBridge -vnc 0.0.0.0:1 centos1708.img
     root       1389   1339   1393  2    3 14:48 pts/0    00:00:36 /usr/libexec/qemu-kvm -cpu SandyBridge -vnc 0.0.0.0:1 centos1708.img
     root       1389   1339   1395  0    3 14:48 pts/0    00:00:00 /usr/libexec/qemu-kvm -cpu SandyBridge -vnc 0.0.0.0:1 centos1708.img
     root       2638   1409   2638  0    1 15:10 pts/1    00:00:00 grep --color=auto qemu
     [root@localhost ~]# taskset -p 1393
     pid 1393's current affinity mask: ff
     [root@localhost ~]# taskset -p 1389
     pid 1389's current affinity mask: ff
     输出结构处理器亲和性掩码是ff,表示进程(或 线程)可以在Host上让任何一个CPU运行。查看进程(或 线程)允许允许CPU范围使用-c参数。由于我的Host CPU是4核2线程,因此有8颗逻辑CPU。
     [root@localhost ~]# taskset -cp 1393
     pid 1393's current affinity list: 0-7
     [root@localhost ~]# taskset -cp 1389
     pid 1389's current affinity list: 0-7
     2.2 更改具体某一进程(或 线程)CPU 绑核
     taskset  -p   hexadecimal mask  PID/LWP
     上面1393号线程可以在0~7号CPU之间允许,现在设置掩码0x11(二进制0001 0001),表示可以在0~4号CPU上允许。
     [root@localhost ~]# taskset -p 0x11  1393
     pid 1393's current affinity mask: ff
     pid 1393's new affinity mask: 11
     [root@localhost ~]# taskset -p   1393
     pid 1393's current affinity mask: 11
     [root@localhost ~]# taskset -cp   1393
     pid 1393's current affinity list: 0,4
     2.3 为具体某一进程(或 线程)CPU 绑核指定一组范围
     使用-c参数
 [root@localhost ~]# taskset -cp 0,3  1393
 pid 1393's current affinity list: 0,4
 pid 1393's new affinity list: 0,3
 [root@localhost ~]# taskset -cp   1393
 pid 1393's current affinity list: 0,3
     2.4 查看某一进程的绑核状态 taskset -cp <pid>
         2.4.1 如果类似下面的显示,说明没绑定:
  [root@iZ25j /]# taskset -c -p 20238
  pid 20238‘s current affinity list:0-3
         2.4.2 如果类似下面的显示,说明绑定到核心 1:
[root@iZ25j /]# taskset -c -p 20239
pid 20238‘s current affinity list:1