You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

chrt -m显示支持SCHED_IDLE但调用sched_setscheduler()时提示‘SCHED_IDLE未声明’的问题求助

解决SCHED_IDLE未声明的编译错误

问题原因

SCHED_IDLE是Linux系统提供的GNU扩展调度策略,并非POSIX标准定义的内容。默认情况下,C标准库的sched.h头文件不会暴露这个常量,因此编译时会提示未声明的错误。此外,你代码中给SCHED_IDLE设置优先级99也是错误的——根据chrt -m的输出,SCHED_IDLE的优先级范围是0/0,只能使用优先级0。

解决步骤

  1. 在所有头文件前定义_GNU_SOURCE宏
    这个宏会告诉C标准库启用所有GNU扩展特性,包括SCHED_IDLE的定义。必须把它放在任何#include语句之前,否则不会生效。

  2. 修正调度优先级为0
    SCHED_IDLE是专为低优先级后台任务设计的,只能使用优先级0,设置其他值会导致sched_setscheduler调用失败。

修正后的完整代码

#define _GNU_SOURCE
#include <unistd.h>
#include <sched.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    int pid_num = getpid();
    struct sched_param sp = { .sched_priority = 0 };
    int ret = sched_setscheduler(pid_num, SCHED_IDLE, &sp);

    if (ret == -1) {
        fprintf(stderr, "Failed to set SCHED_IDLE: %s\n", strerror(errno));
        return 1;
    }

    printf("Successfully set SCHED_IDLE scheduler for current process\n");
    return 0;
}

编译与验证

编译代码时无需额外链接选项:

gcc -o set_idle_sched set_idle_sched.c

运行后可以用chrt命令验证调度策略是否生效:

chrt -p $(pgrep set_idle_sched)

输出应该会显示policy: 5 (SCHED_IDLE)。

补充说明

你的系统内核版本5.13.0-27-generic完全支持SCHED_IDLE,chrt -m的输出也证实了这一点,所以问题只出在编译时的宏定义和代码中的优先级错误上。

内容的提问来源于stack exchange,提问作者mahmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:38:12