Reputation: 389
I'm trying to run a process on a specific CPU I specify in my C program periodically on my Linux machine. I am not sure how to specify inside my program the specific CPU the process needs to run on.
I have been reading about ways to do this on the command line, but I can't find much on how to do this inside a program in C itself.
I know there is the task_struct
in the directory include/linux/sched.h
. Upon inspecting the struct, I see multiple fields regarding the CPU. But I am reading (To access PCB of process in C) that accessing task/process info is not advised or easy at all.
I'm also reading up on the "current" macro, but I'm not sure if this is relevant to my issue.
My program is really simple and is just basically a test showing how I can run a task periodically on a certain CPU.
Does anyone have knowledge of how I can accomplish this simple specification?
Upvotes: 1
Views: 243
Reputation: 75555
This thing you are trying to do is called thread pinning.
It looks like you want sched_setaffinity. You can invoke it from inside your application with the getpid()
system call.
#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);
Upvotes: 3