36.6. 显示进程的调度策略和相关属性
sched_getattr () 函数查询当前应用到指定进程的调度策略,由 PID 标识。如果 PID 等于零,则检索调用进程的策略。
size 参数应反映 sched_attr 结构的大小,如用户空间所知的。内核将 sched_attr::size 填充到其 sched_attr 结构的大小。
如果输入结构较小,内核会返回提供空间之外的值。因此,系统调用会失败,并显示 E2BIG 错误。其他 sched_attr 字段已填写,如 sched_attr 结构 中所述。
流程
创建
sched_timeslice.c源文件,并在文本编辑器中打开该文件。$ {EDITOR} sched_timeslice.c将以下行添加到
sched_timeslice.c文件中。#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; }编译
sched_timeslice.c文件。$ gcc sched_timeslice.c -o sched_timeslice检查
sched_timeslice程序的输出。$ ./sched_timeslice 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