41.6. 显示进程的调度策略和相关属性
sched_getattr()
函数查询当前应用于由 PID 识别的指定进程的调度策略。如果 PID 等于零,则检索调用进程的策略。
size
参数应反映对用户空间所知的 sched_attr 结构的大小。内核将 sched_attr::size 填充到其 sched_attr 结构的大小。
如果输入结构比较小,内核将返回所提供空间之外的值。因此,系统调用会失败并显示 E2BIG
错误。其他 sched_attr 字段已填写,如 sched_attr 结构 中所述。
流程
运行以下代码。
#define _GNU_SOURCE #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <linux/unistd.h> #include <linux/kernel.h> #include <linux/types.h> #include <sys/syscall.h> #include <pthread.h> #define gettid() syscall(NR_gettid) #define SCHED_DEADLINE 6 /* XXX use the proper syscall numbers / #ifdef x86_64 #define NR_sched_setattr 314 #define NR_sched_getattr 315 #endif struct sched_attr { u32 size; u32 sched_policy; u64 sched_flags; / SCHED_NORMAL, SCHED_BATCH / s32 sched_nice; / SCHED_FIFO, SCHED_RR / u32 sched_priority; / SCHED_DEADLINE (nsec) */ u64 sched_runtime; u64 sched_deadline; u64 sched_period; }; int sched_getattr(pid_t pid, struct sched_attr *attr, unsigned int size, unsigned int flags) { return syscall(NR_sched_getattr, pid, attr, size, flags); } int main (int argc, char **argv) { struct sched_attr attr; unsigned int flags = 0; int ret; ret = sched_getattr(0, &attr, sizeof(attr), flags); if (ret < 0) { perror("sched_getattr"); exit(-1); } printf("main thread pid=%ld\n", gettid()); printf("main thread policy=%ld\n", attr.sched_policy); printf("main thread nice=%ld\n", attr.sched_nice); printf("main thread priority=%ld\n", attr.sched_priority); printf("main thread runtime=%ld\n", attr.sched_runtime); printf("main thread deadline=%ld\n", attr.sched_deadline); printf("main thread period=%ld\n", attr.sched_period); return 0; }
输出示例
main thread pid=321716 main thread policy=6 main thread nice=0 main thread priority=0 main thread runtime=1000000 main thread deadline=9000000 main thread period=10000000