概述:
最近接触到关于linux调度的一些相关内容,这里做个总结笔记。这里主要学习到三种调度策略,SCHED_RR,SCHED_FIFO,SCHED_OTHER这三种。具体详细的内容就不多说,已经有很多详细的介绍了。这里记录下怎么查看某个进程或线程的调度策略和优先级,以及怎么修改别的进程或线程的优先级。
快速查看进程优先级和调度策略:
找到某个进程或线程ID,通过查看此进程或线程下的sched文件查看调度策略和优先级
函数设置和获取优先级和调度策略(自己写的一个简单程序):
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define TYPE_GET 0
#define TYPE_SET 1
#define SCHED_OTHER 0
#define SCHED_FIFO 1
#define SCHED_RR 2
static const struct {
char name[sizeof("SCHED_OTHER")];
} policies[] = {
{ "SCHED_OTHER" }, /* 0:SCHED_OTHER */
{ "SCHED_FIFO" }, /* 1:SCHED_FIFO */
{ "SCHED_RR" }, /* 2:SCHED_RR */
{ "SCHED_BATCH" }, /* 3:SCHED_BATCH */
{ "" }, /* 4:SCHED_ISO */
{ "SCHED_IDLE" }, /* 5:SCHED_IDLE */
/* 6:SCHED_DEADLINE */
};
int main(int argc, char **argv)
{
int i = 0, tmp_pid = 0, type = 0;
int method = 0, prio = 0;
int pol;
pid_t pid = 0;
if (argc != 3 && argc != 5)
{
printf("argc is %d not support\n", argc);
return -1;
}
tmp_pid = atoi(argv[1]);
type = atoi(argv[2]);
pid = tmp_pid;
struct sched_param sp;
memset((char*)&sp, 0, sizeof(sp));
pol = sched_getscheduler(pid);
if (pol < 0)
{
printf("sched_getscheduler error\n");
return 0;
}
if (sched_getparam(pid, &sp))
{
printf("sched_getparam error\n");
return 0;
}
if (TYPE_SET == type)
{
if (argc != 5)
{
printf("argc is %d, param error\n", argc);
return -1;
}
else
{
method = atoi(argv[3]);
if (method < SCHED_OTHER || method > SCHED_RR)
{
printf("method is %d not support\n", argc);
return -1;
}
prio = atoi(argv[4]);
int min = 0, max = 0;
min = sched_get_priority_min(method);
max = sched_get_priority_max(method);
if (prio < min || prio > max)
{
printf("min is %d max is %d set prio %d not support\n", min, max, prio);
return -1;
}
}
printf("SET: %d %d %d %d\n", tmp_pid, type, method, prio);
sp.sched_priority = prio;
if (sched_setscheduler(pid, method, &sp) < 0)
{
printf("sched_setscheduler is failed\n");
return -1;
}
printf("Set pid %d's is Success\n", (int)pid);
}
else
{
printf("GET: %d %d\n", tmp_pid, type);
printf("pid %d's scheduling policy: %s\n", (int)pid, policies[pol].name);
printf("pid %d's scheduling priority: %d\n", (int)pid, sp.sched_priority);
}
}
运行结果:
特别说明:
对于调度策略为SCHED_OTHER的进程或线程,通过上诉设置优先级一般是无效的,而且其最大最小值优先级获取是0,如果想要修改优先级则需使用nice函数进行修改。
参考资料:
linux进程调度方法(SCHED_OTHER,SCHED_FIFO,SCHED_RR)