c - 针对比使用 libc 构建的更新的 linux 头文件构建

标签 c linux system-calls libc sched-deadline

我想使用新的 SCHED_DEADLINE 编写程序调度策略可用 since Linux 3.14 .

我从一个尝试使用 sched_setattr 的简单程序开始功能。

#include <sched.h>

int main(void)
{
    // struct sched_attr attr;
    // attr.size = sizeof(struct sched_attr);
    // attr.sched_policy = SCHED_DEADLINE;
    sched_setattr(0, (void*)0, 0);

    return 0;
}

但是在编译时出现以下错误:

$gcc dead.c 
dead.c: In function ‘main’:
dead.c:8:2: warning: implicit declaration of function ‘sched_setattr’ [-Wimplicit-function-declaration]
  sched_setattr(0, (void*)0, 0);
  ^~~~~~~~~~~~~
/tmp/ccGxWxZE.o: In function `main':
dead.c:(.text+0x19): undefined reference to `sched_setattr'
collect2: error: ld returned 1 exit status

我的系统运行的是 Ubuntu 16.10 Yakkety,内核为 4.8.0-59-generic。 sched.h包含的文件位于 /usr/include/sched.h 中由包提供 libc6-dev .此头文件不包含函数 sched_setattr和我正在尝试使用的 friend 。

但是我安装的内核(和内核头文件)带有 sched.h包含我需要的定义的头文件。它位于 /usr/src/linux-headers-4.8.0-58/include/linux/sched.h , 在我的系统上。

所以我天真地认为让我们只针对较新的 linux header 而不是 libc6-dev 提供的 header 进行构建。我的程序只能在这个或更新的内核上运行,但这很好。

我将第一行修改为:#include <linux/sched.h>并执行:

gcc -I/usr/src/linux-headers-$(uname -r)/include -I/usr/src/linux-headers-$(unam -r)/arch/x86/include dead.c

现在我看到一页又一页的错误和警告。这似乎不是要走的路。

针对比 libc 提供的更新的 Linux header 构建用户空间程序的正确方法是什么?

然后我该如何构建上面的程序?

最佳答案

sched_setattr() 是一个系统调用,似乎没有一对一的 libc 包装器。你可以自己做包装器,像这样:

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <linux/sched.h>
#include <sys/syscall.h>
#include <sys/types.h>

struct sched_attr {
    uint32_t size;              /* Size of this structure */
    uint32_t sched_policy;      /* Policy (SCHED_*) */
    uint64_t sched_flags;       /* Flags */
    int32_t sched_nice;         /* Nice value (SCHED_OTHER, SCHED_BATCH) */
    uint32_t sched_priority;    /* Static priority (SCHED_FIFO, SCHED_RR) */
    /* Remaining fields are for SCHED_DEADLINE */
    uint64_t sched_runtime;
    uint64_t sched_deadline;
    uint64_t sched_period;
};

static int sched_setattr (pid_t pid, const struct sched_attr *attr, unsigned int flags)
{
    return syscall (SYS_sched_setattr, pid, attr, flags);
}

int main (int argc, char *argv[])
{
    struct sched_attr attr;
    int res;

    memset (&attr, 0, sizeof (struct sched_attr));
    attr.size = sizeof (struct sched_attr);

    res = sched_setattr (getpid (), &attr, 0);
    if (res < 0) {
        perror ("sched_setattr");
        return 1;
    }

    return 0;
}

查看在尝试包含获取 struct sched_attr 定义所需的内核头文件时报告的错误,并阅读通过谷歌搜索“用户空间中的内核头文件”找到的评论,我真的不能建议为此尝试包含内核头文件。

关于c - 针对比使用 libc 构建的更新的 linux 头文件构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45692699/

相关文章:

c - 查找文件操作的 CPU 使用率

c - 如何捕获系统范围内加载的库?

linux - 如何跳过安装两次的目录?

linux - 如何在 Linux (Centos) 机器上安装此软件包?

golang 在 syscall.Mount 中没有这样的设备

c - 在 C 中使用 WEXITSTATUS 宏比在 exit() 状态上除以 256 有什么好处?

c - 在 C 中查找主机地址范围

c - 如何在 C 中声明依赖结构?

c - 这个内存分配器是如何工作的?

linux - 汇编程序 sysTime 在执行时给出错误