c - perf_event_open 的权限被拒绝,除了使用 sudo 或更改 perf_event_paranoid 文件之外,还有其他方法吗?

标签 c permissions perf

我能找到的有关该主题的唯一信息是此链接:perf_event_open always returns -1 ,根据我的理解,建议使用 CONFIG_HW_PERF_EVENTS 进行配置,但我仍然遇到同样的问题。

我正在实现一个受 perf_event_open 手册页启发的程序:

static long
       perf_event_open(struct perf_event_attr *hw_event, pid_t pid,
                       int cpu, int group_fd, unsigned long flags)
       {
           int ret;

           ret= syscall(__NR_perf_event_open, hw_event, pid, cpu,
                          group_fd, flags);
           return ret;
       }
struct perf_event_attr pe;

int pid = fork();

if (pid > 0 ) {

memset(&pe, 0, sizeof(pe));
           pe.type = PERF_TYPE_HARDWARE;
           pe.size = sizeof(pe);
           pe.config = PERF_COUNT_HW_CPU_CYCLES;
           pe.disabled = 0;
           pe.exclude_kernel = 0;
           pe.exclude_hv = 0;   
            
           fd = perf_event_open(&pe, pid, -1, -1, 0);
if (fd == -1) {
               perror(0);
              exit(EXIT_FAILURE);
           }
}

我总是得到 fd 的 -1 返回值,并且 perror 表示权限被拒绝。

当然,我可以使用 sudo 解决该问题,但是还有其他方法可以允许执行 perf_event_open 的权限吗?

PS:我不想更改perf_event_paranoid文件,这使得程序在设置为-1时可以工作;我猜应该是 2 点。

最佳答案

RETURN VALUE section of the Linux perf_event_open() system call部分说明:

   ...

   EACCES Returned when the requested event requires CAP_PERFMON
          (since Linux 5.8) or CAP_SYS_ADMIN permissions (or a more
          permissive perf_event paranoid setting).  Some common
          cases where an unprivileged process may encounter this
          error: attaching to a process owned by a different user;
          monitoring all processes on a given CPU (i.e., specifying
          the pid argument as -1); and not setting exclude_kernel
          when the paranoid setting requires it.

   ...

   EPERM  Returned on many (but not all) architectures when an
          unsupported exclude_hv, exclude_idle, exclude_user, or
          exclude_kernel setting is specified.

          It can also happen, as with EACCES, when the requested
          event requires CAP_PERFMON (since Linux 5.8) or
          CAP_SYS_ADMIN permissions (or a more permissive perf_event
          paranoid setting).  This includes setting a breakpoint on
          a kernel address, and (since Linux 3.13) setting a kernel
          function-trace tracepoint.

从发布的示例代码中,考虑到您关于偏执设置的声明,值 pe.exclude_kernel = 0;pe.exclude_hv = 0; 可能会导致权限问题.

关于c - perf_event_open 的权限被拒绝,除了使用 sudo 或更改 perf_event_paranoid 文件之外,还有其他方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66146189/

相关文章:

linux - 使用 perf 了解内存压力

c - UDP 和套接字,recvfrom() 返回 -1 且资源暂时不可用

c - 这是以微秒为单位的返回时间吗?

c - Piketec TPT java 自动化

git fetch 权限不足,无法将对象添加到存储库数据库 .git/objects?

ubuntu 12.10 perf stat <不支持> 周期

C 编程 - 计算 2 个日期时间的差异

C - 阻止其他人写入文件

ruby - Jekyll:不允许操作@apply2files

linux - 在 Linux-4.4.0 中 PTI=on 性能下降