Post

Fun with realtime scheduler (2)

Who needs chrt when you can set things yourself from C code?

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <sched.h>
#include <unistd.h>

void setscheduler(void)
{
    struct sched_param sched_param;

    if (sched_getparam(0, &sched_param) < 0) {
        printf("Scheduler getparam failed...\n");
        return;
    }
    sched_param.sched_priority = 99;
    if (!sched_setscheduler(0, SCHED_FIFO, &sched_param)) {
        printf("Scheduler set to SCHED_FIFO with priority %i...\n", sched_param.sched_priority);
        return;
    }
    printf("!!!Scheduler set to SCHED_FIFO with priority %i FAILED!!!\n", sched_param.sched_priority);
}

int main()
{
    setscheduler();

    while(1)
    {
        printf("PID %i sleeping..\n", getpid());
        sleep(5);
    }
}

Output:

1
2
3
4
gcc setscheduler.c -o setscheduler
./setscheduler
Scheduler set to SCHED_FIFO with priority 99...
PID 5193 sleeping..

To confirm that it works we run chrt in another terminal:

1
2
3
benjamin@laptop:~$ chrt -p 5193
pid 5193's current scheduling policy: SCHED_FIFO
pid 5193's current scheduling priority: 99
This post is licensed under CC BY 4.0 by the author.