【问题标题】:runtime error in scheduling the tasks in realtime linux?在实时linux中调度任务时出现运行时错误?
【发布时间】:2014-04-01 10:09:17
【问题描述】:
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE   500

#include <sched.h>  /* for sched_setsched */
#include <unistd.h> /* for usleep */
#include <time.h>   /* for clock_gettime */
#include <string.h> /* for memset */
#include <stdio.h>

#define MS_to_US(x) ((x)*1000)

void TASK1()
{
    printf("hi \n");
}

void TASK2()
{
    printf("hi2 \n");
}

void TASK3()
{
    printf("hi3 \n");
}

useconds_t delta_t_us(struct timespec const *a, struct timespec const *b)
{
    time_t const delta_sec  = b->tv_sec  - a->tv_sec;
    long   const delta_nsec = b->tv_nsec - a->tv_nsec;

    /* this might actually overflow for "long" time intervalls"
     * should be safe for a delta_t < 2ms though */
    return delta_sec * 1000000 + delta_nsec / 1000;
}

void rastertask()
{
    struct sched_param sparm;
    memset(&sparm, 0, sizeof(sparm));
    sparm.sched_priority = 10; /* 0 = lowest, 99 = highest */

    sched_setscheduler(
        0 /* pid, 0 ==> this process */,
        SCHED_RR /* policy */,
        &sparm);

    unsigned int n_loop;
    for(n_loop=0;;n_loop++) {
        struct timespec ts_start, ts_end;
        clock_gettime(CLOCK_REALTIME, &ts_start);

        TASK1(); /* gets called every 2ms */
        if( (n_loop % 5) == 0) {
            TASK2(); /* get called every 5 * 2ms = 10ms */
        }
        if( (n_loop % 50) == 0) {
            TASK2(); /* get called every 50 * 2ms = 100ms */
        }

        if( (n_loop % 250) == 0 ) {
            /* reset loop counter when smallest common
             * multiple of timing grid has been reached */
            n_loop = 0;
        }

        clock_gettime(CLOCK_REALTIME, &ts_end);
        useconds_t const tasks_execution_time = delta_t_us(&ts_start, &ts_end);

        if( tasks_execution_time >= MS_to_US(2) ) {
            /* report an error that tasks took longer than 2ms to execute */
        }

        /* wait for 2ms - task_execution_time so that tasks get called in
         * a close 2ms timing grid */
        usleep( MS_to_US(2) - tasks_execution_time );
    }
}

int main()
{
    rastertask();
    return 1;
}

我创建了一个调度程序,用于每 2ms(毫秒)、10ms 和 100ms 调度任务。上面的代码正在编译并且正在运行。运行一段时间后,调度程序将停止执行任务。调度程序每 2 毫秒、10 和 100 毫秒调用三个任务。任务是打印 hi、hi1 和 hi3

问题:为什么上面的代码在 100 毫秒内没有打印 hi3 ? 为什么它会在一定时间后停止??

【问题讨论】:

    标签: c linux timer real-time interrupt


    【解决方案1】:

    问题 1) TASK3 未执行,因为您没有调用它。 TASK2 在两个 if 语句之后调用

    问题 2) if (tasks_execution_time 大于 2ms: MS_to_US(2) - tasks_execution_time 将为负数,usleep 将等待很长时间。我建议在 usleep 之前使用“else”,因为 if 已经在检查这个。

    【讨论】:

    • @Jayesh 它可能会像这里提到的那样停止,因为一个负时间被传递给了我们睡眠。例如delta_t_us 函数是错误的(它盲目地减去纳秒部分,而它应该检查下溢并从秒中减去 1 并重新调整纳秒部分),并且很容易得到意想不到的值。
    • @all:非常感谢。我根据 gato 添加了其他内容,它工作正常。
    猜你喜欢
    • 2015-10-10
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多