如何包含linux / getcpu.h等Linux头文件?

时间:2014-04-22 16:03:29

标签: c linux include-path

我正在使用Linux 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:31:23 UTC 2012 x86_64 GNU/Linux,我需要#include<linux/getcpu.h>。编译器抱怨它无法找到该文件。 linux的头文件在哪里?

2 个答案:

答案 0 :(得分:5)

简短回答:通常,您不直接包含这些标题。

其中大多数OS / Machine特定的标头都会由更通用的标头自动包含在内。那些不是Linux的功能可能会或可能不适用于您正在运行的版本。

至于getcpu,有一个名为sched_getcpu的标准化版本,可在sched.h中找到并具有相同的功能。

或者,您可以测试系统上是否有可用的系统调用并手动调用它:

#define _GNU_SOURCE  
#include <unistd.h>
#include <sys/syscall.h>

static inline int getcpu() {
    #ifdef SYS_getcpu
    int cpu, status;
    status = syscall(SYS_getcpu, &cpu, NULL, NULL);
    return (status == -1) ? status : cpu;
    #else
    return -1; // unavailable
    #endif
}

变量errno(#include <errno.h>)给出错误代码,如果syscall返回-1。

答案 1 :(得分:1)

glibc现在在getcpu()下定义了sched.h

从Ubuntu 20.04 glibc 2.31开始经过测试,#include <sched.h>已经通过getcpu定义了原型的#include <bits/sched.h>函数:

extern int getcpu (unsigned int *, unsigned int *) __THROW;

看起来不错:

getcpu.c

#define _GNU_SOURCE
#include <assert.h>
#include <sched.h> /* getcpu */
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

void* main_thread(void *arg) {
    (void)arg;
    unsigned cpu, numa;
    getcpu(&cpu, &numa);
    printf("%u %u\n", cpu, numa);
    return NULL;
}

int main(int argc, char **argv) {
    pthread_t *threads;
    unsigned int nthreads, i;
    if (argc > 1) {
        nthreads = strtoll(argv[1], NULL, 0);
    } else {
        nthreads = 1;
    }
    threads = malloc(nthreads * sizeof(*threads));
    for (i = 0; i < nthreads; ++i) {
        assert(pthread_create(
            &threads[i],
            NULL,
            main_thread,
            NULL
        ) == 0);
    }
    for (i = 0; i < nthreads; ++i) {
        pthread_join(threads[i], NULL);
    }
    free(threads);
    return EXIT_SUCCESS;
}

GitHub upstream

编译并运行:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o getcpu.out getcpu.c -pthread
./getcpu.out 4

我的8核笔记本电脑上的示例输出:

5 0
4 0
7 0
3 0

man getcpu说可以在#include <linux/getcpu.h>中找到它,但这对我的系统来说是错误的。 locate getcpu.h显示他唯一的命中是:/usr/src/linux-headers-5.4.0-29/include/linux/getcpu.h,但这仅定义了struct getcpu_cache,没有其他内容。