运行 Linux 中特定 CPU 的进程? (不能用命令行指定)

Run a process on a specific CPU in Linux? (can't use command line to specify)

我正在尝试 运行 在我的 Linux 机器上定期在我的 C 程序中指定的特定 CPU 上的进程。我不确定如何在我的程序中指定进程需要 运行 的特定 CPU。

我一直在阅读有关在命令行上执行此操作的方法,但我找不到太多关于如何在 C 本身的程序中执行此操作的信息。

我知道 include/linux/sched.h 目录下有 task_struct。检查该结构后,我看到了多个有关 CPU 的字段。但我读到 (To access PCB of process in C) 访问 task/process 信息是不被建议的,而且根本不方便。

我也在阅读 "current" 宏,但我不确定这是否与我的问题相关。

我的程序非常简单,基本上只是一个测试,展示了我如何 运行 在某个 CPU 上定期执行任务。

有谁知道我如何完成这个简单的规范?

你正在尝试做的这件事叫做线程固定。

您似乎需要 sched_setaffinity. You can invoke it from inside your application with the getpid() 系统调用。

   #include <sched.h>

   int sched_setaffinity(pid_t pid, size_t cpusetsize,
                         const cpu_set_t *mask);

   int sched_getaffinity(pid_t pid, size_t cpusetsize,
                         cpu_set_t *mask);