Fun with realtime scheduler (2)

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

Example:

#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:

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:

benjamin@laptop:~$ chrt -p 5193
pid 5193's current scheduling policy: SCHED_FIFO
pid 5193's current scheduling priority: 99