隐式声明函数'sched_setaffinity'

Muh*_*waz 6 c linux ubuntu gcc scheduled-tasks

我正在编写一个需要在单核上运行的程序.要将它绑定到单核,我正在使用sched_setaffinity(),但编译器发出警告:

implicit declaration of function ‘sched_setaffinity’

我的测试代码是:

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

int main()
{
    unsigned long cpuMask = 2;
    sched_setaffinity(0, sizeof(cpuMask), &cpuMask);
    printf("Hello world");
    //some other function calls
}
Run Code Online (Sandbox Code Playgroud)

能帮我解决一下吗?实际上代码是经过编译和运行的,但我不确定它是在单核上运行还是在交换内核.

我使用的是Ubuntu 15.10和gcc 5.2.1版

Ark*_*zyk 10

你需要移到#define _GNU_SOURCE顶部.在man sched_setaffinity其中说:

 #define _GNU_SOURCE             /* See feature_test_macros(7) */
Run Code Online (Sandbox Code Playgroud)

man 7 feature_test_macros里面说:

注意:为了有效,必须在包含任何头文件之前定义功能测试宏.这可以在编译命令(cc -DMACRO = value)中完成,也可以在包含任何头之前在源代码中定义宏.

因此,在一天结束时,您的代码应如下所示:

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


int main()
{
    unsigned long cpuMask = 2;
    sched_setaffinity(0, sizeof(cpuMask), &cpuMask);
    printf("Hello world");
    //some other function calls
}
Run Code Online (Sandbox Code Playgroud)