gpt4 book ai didi

c - linux 实时调度任务时出现运行时错误?

转载 作者:行者123 更新时间:2023-11-30 19:20:12 24 4
gpt4 key购买 nike

#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 调度一次任务。上面的代码正在编译并且正在运行。运行一定时间后,调度程序将停止执行任务。调度程序每 2ms、10 和 100ms 调用三个任务。任务正在打印 hi、hi1 和 hi3

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

最佳答案

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

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

关于c - linux 实时调度任务时出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com