The Linux taskset
command is a command line utility that is used to set or retrieve the CPU affinity of a running process. CPU affinity determines which CPU or CPUs a process is allowed to run on, and it can be useful for optimizing the performance of a system by ensuring that processes are running on the most appropriate CPU or CPUs.
To use the taskset
command, you first need to know the PID (process ID) of the process that you want to set the CPU affinity for. You can use the ps
command or the top
command to view a list of running processes and their PIDs.
Once you know the PID of the process, you can use the taskset
command to set the CPU affinity for the process. To do this, you use the -p
option followed by the PID of the process, and then specify the CPU or CPUs that the process should be allowed to run on.
For example, to set the CPU affinity for process ID 1234
to CPU 0
, you would use the following command:
$ taskset -p 0 1234
pid 1234's current affinity mask: 1
pid 1234's new affinity mask: 1
The taskset
command will then set the CPU affinity for the process, and display the current and new affinity masks for the process.
The taskset
command also has a number of other options that can be used to control its behavior. For example, the -c
option allows you to specify the CPU or CPUs that the process should be allowed to run on using a comma-separated list of CPU numbers, rather than a CPU affinity mask.
For example, to set the CPU affinity for process ID 1234
to CPUs 0
and 1
, you could use the following command:
$ taskset -c 0,1 -p 1234
pid 1234's current affinity mask: 1
pid 1234's new affinity mask: 3
This would set the CPU affinity for the process to CPUs 0
and 1
, allowing the process to run on either of these CPUs.
The taskset
command can also be used to retrieve the current CPU affinity for a process. To do this, you use the -p
option followed by the PID of the process, but you do not specify any CPUs. For example:
$ taskset -p 1234
pid 1234's current affinity mask: 3
This would display the current CPU affinity mask for the process with PID 1234
, indicating which CPUs the process is allowed to run on.
In conclusion, the taskset
command is a useful tool for controlling the CPU affinity of processes on a Linux system. By setting the CPU affinity for a process, you can ensure that it is running on the most appropriate CPU or CPUs, which can help to optimize the performance of the system. Whether you are a developer or a system administrator, the taskset
command is a valuable tool to have in your toolkit.