加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

在Linux上以root用户身份调用SCHED_FIFO线程的pthread_create()

发布时间:2020-12-14 01:00:06 所属栏目:Linux 来源:网络整理
导读:我试图在 Linux系统上以root身份生成带有SCHED_FIFO或SCHED_RR策略的线程,但是我对pthread_create()的调用返回1(EPERM). pthread_create()的手册页说EPERM表示“调用者没有适当的权限来设置所需的调度参数或调度策略.”不应该root能够指定SCHED_FIFO或SCHED_
我试图在 Linux系统上以root身份生成带有SCHED_FIFO或SCHED_RR策略的线程,但是我对pthread_create()的调用返回1(EPERM). pthread_create()的手册页说EPERM表示“调用者没有适当的权限来设置所需的调度参数或调度策略.”不应该root能够指定SCHED_FIFO或SCHED_RR吗?

我已经删除了将一个线程创建到一个只执行该操作的小程序中的代码.它看起来对我来说,但仍然得到错误.我究竟做错了什么?

该程序:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

static void *_Thread(void *arg)
{
    (void)arg;
    printf("Thread running!n");
    return NULL;
}

int main(void)
{
    int retVal;
    pthread_attr_t attr;
    struct sched_param schedParam;
    pthread_t thread;

    retVal = pthread_attr_init(&attr);
    if (retVal)
    {
        fprintf(stderr,"pthread_attr_init error %dn",retVal);
        exit(1);
    }

    retVal = pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED);
    if (retVal)
    {
        fprintf(stderr,"pthread_attr_setinheritsched error %dn",retVal);
        exit(1);
    }

    retVal = pthread_attr_setschedpolicy(&attr,SCHED_FIFO);
    if (retVal)
    {
        fprintf(stderr,"pthread_attr_setschedpolicy error %dn",retVal);
        exit(1);
    }

    schedParam.sched_priority = 1;
    retVal = pthread_attr_setschedparam(&attr,&schedParam);
    if (retVal)
    {
        fprintf(stderr,"pthread_attr_setschedparam error %dn",retVal);
        exit(1);
    }

    retVal = pthread_create(&thread,&attr,_Thread,NULL);
    if (retVal)
    {
        fprintf(stderr,"pthread_create error %dn",retVal);
        exit(1);
    }

    retVal = pthread_join(thread,"pthread_join error %dn",retVal);
        exit(1);
    }

    printf("main run successfullyn");
    return 0;
}

该程序已编译并以root身份运行.运行时,程序在调用pthread_create时失败,返回EPERM.

将线程更改为SCHED_RR调度没有任何效果 – 仍然由pthread_create返回EPERM.

将线程更改为SCHED_OTHER调度并将其优先级更改为0允许程序无错误地运行.

解决方法

必须是您的实时优先级软限制过于严格.

在运行代码之前,在shell中调用ulimit -r unlimited.或者直接在代码中调用setrlimit(RLIMIT_RTPRIO,…).

系统范围的限制在/etc/security/limits.conf中设置.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读