首页 > 解决方案 > 在 Linux 内核中使用“sched_setaffinity()”

问题描述

很多帖子sched_setaffinity,但几乎没有关于在内核空间中使用它的帖子。

我在内核 4.14.79 上。

我尝试使用以下形式调用的用户空间方法sched_setaffinity

cpu_set_t my_set;        
CPU_ZERO(&my_set);       
CPU_SET(7, &my_set);     
sched_setaffinity(0, sizeof(cpu_set_t), &my_set);

但是在尝试编译内核时,我遇到了错误并意识到这种形式在内核空间中不起作用。

我看到它sched_affinity被定义sched.h并具有以下形式:

extern long sched_setaffinity(pid_t pid, const struct cpumask *new_mask);

但是我对如何正确创建new_mask具有正确 CPU 编号的参数感到困惑。它的文档不是很有帮助。

有人可以举例说明如何在内核空间中使用此函数将进程设置为特定 CPU 吗?

标签: linuxkernelsystem-calls

解决方案


在挖掘内核文件以寻找cpumask出现的位置后,我自己找到了答案。

您可以使用这两个功能:

cpumask_clear(struct cpumask *dstp) //clear the mask you are about to use

cpumask_set_cpu(unsigned int cpu, struct cpumask *dstp) //set the cpu number

所以我用的是这样的东西:

struct cpumask mask;  
cpumask_clear(&mask); 
cpumask_set_cpu(cpuNumber, &mask); 
sched_setaffinity(pid, &mask); 

推荐阅读