Linux 更改进程调度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flyfish1986/article/details/82225937

Linux 更改进程调度

flyfish

RR、FIFO、OTHER等三种调度

命令行实现

查看进程优先级
chrt -p 9104
pid 9104’s current scheduling policy: SCHED_OTHER
pid 9104’s current scheduling priority: 0

更改进程优先级
sudo chrt -p 10 9104

chrt -p 9104
pid 9104’s current scheduling policy: SCHED_RR
pid 9104’s current scheduling priority: 10

代码实现 Qt编译通过

#include <sched.h>
#include <sys/types.h>
#include <unistd.h>
#include <QMessageBox>
#include <string>
#include <sstream>


//设置实时进程
struct sched_param param;
param.sched_priority = 10;

std::stringstream s;
s << getpid();
QMessageBox::information(NULL, "Title", s.str().c_str(), QMessageBox::Yes, QMessageBox::Yes);

if (sched_setscheduler(getpid(), SCHED_RR, &param) == -1) 
{
    QString Content = "sched_setscheduler() failed";
    QMessageBox::information(NULL, "Title", Content, QMessageBox::Yes, QMessageBox::Yes);
    exit(1);
}

如果设置FIFO

struct sched_param param;
int maxpri=0;
maxpri = sched_get_priority_max(SCHED_FIFO); 
if (maxpri == -1)
{
    QString Content = "sched_get_priority_max() failed";
    QMessageBox::information(NULL, "Title", Content, QMessageBox::Yes, QMessageBox::Yes);
    exit(1);
}
param.sched_priority = maxpri;

std::stringstream s;
s << getpid();
QMessageBox::information(NULL, "Title", s.str().c_str(), QMessageBox::Yes, QMessageBox::Yes);

if (sched_setscheduler(getpid(), SCHED_FIFO, &param) == -1) 
{
    QString Content = "sched_setscheduler() failed";
    QMessageBox::information(NULL, "Title", Content, QMessageBox::Yes, QMessageBox::Yes);
    exit(1);
}

Python实现
python3.3以后都有sched_setscheduler函数的实现
以下时python 2.7的实现,因为Python2.7中没有,所有需要从c库中使用该函数

https://docs.python.org/3/library/ctypes.html

代码段实验

from ctypes import *
lib = CDLL("libc.so.6")
printf = lib.printf
printf("Hello World\n") 

from ctypes.util import find_library
print find_library('c')
CDLL(find_library("c")).printf 

import ctypes.util
c = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))
print c

输出
Hello World
libc.so.6
<CDLL 'libc.so.6', handle 7f2466bd54e8 at 7f2463d6e490>

代码实现

import sys

try:
    import ctypes
    import ctypes.util
    c = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))
    importCtypesFailed = False
except Exception:
    importCtypesFailed = True

SCHED_NORMAL = 0
SCHED_FIFO = 1
SCHED_RR = 2
SCHED_BATCH = 3

if not importCtypesFailed:
    class _SchedParams(ctypes.Structure):
        _fields_ = [('sched_priority', ctypes.c_int)]

def SetSchedulerPrivilege():
    if importCtypesFailed:
        return False

    schedParams = _SchedParams()
    schedParams.sched_priority = c.sched_get_priority_max(SCHED_RR)
    err = c.sched_setscheduler(0, SCHED_RR, ctypes.byref(schedParams))

    return True

猜你喜欢

转载自blog.csdn.net/flyfish1986/article/details/82225937