【问题标题】:How to set IRQ priority in Linux from C/C++?如何从 C/C++ 在 Linux 中设置 IRQ 优先级?
【发布时间】:2017-03-09 13:21:54
【问题描述】:

现在我正在使用chrt(对于给定的 irqPid)在实时 Linux 中设置 IRQ 优先级:

/usr/bin/chrt -f -p 95 irqPid

有没有办法/一些函数从 C/C++ 中做到这一点(除了运行 system() 来执行上面的命令)?

【问题讨论】:

标签: c++ c linux system-calls interrupt


【解决方案1】:

你可能想要sched_setattr。使用 strace 可以很简单地查看 chrt 正在使用什么系统调用。

$ sleep 10 &
[2] 3590
$ sudo strace -- /usr/bin/chrt -f -p 95 $! 2>&1 | grep "=95"
sched_setattr(3590, {size=48, sched_policy=SCHED_FIFO, sched_flags=0, sched_nice=0, sched_priority=95, sched_runtime=0, sched_deadline=0, sched_period=0}, 0) = 0

为当前进程执行此操作的一些代码如下所示:

#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.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, char**) {
    int result;
    struct sched_attr attr;
    memset(&attr, 0, sizeof(attr));
    attr.size = sizeof(sched_attr);
    attr.sched_priority = 95;
    attr.sched_policy = SCHED_FIFO;
    result = sched_setattr(getpid(), &attr, 0);
    if (result == -1) {
        perror("Error calling sched_setattr.");
    }
}

在编译后的文件上再次使用 strace:

$ sudo strace ./a.out 2>&1 | grep "=95"
sched_setattr(4889, {size=48, sched_policy=SCHED_FIFO, sched_flags=0, sched_nice=0, sched_priority=95, sched_runtime=0, sched_deadline=0, sched_period=0}, 0) = 0

由于某种原因,我在我的系统上找不到 glibc 中的系统调用或 sched.h 中的结构,所以我必须包含结构和系统调用定义。我对此了解不多,所以这个函数可能比需要的级别更低,更高级别的调用可以更轻松地完成您想要的操作,但这恰恰反映了 chrt 正在做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多