我能找到的关于这个主题的唯一信息是这个链接:perf_event_open总是返回-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点。
返回值Linuxperf_event_open()
系统调用状态的部分:
... 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;
可能会导致关于偏执设置的声明的权限问题。