c - 尝试映射设备的 BAR-0 时出现“错误的文件描述符”错误
问题描述
我正在尝试将 PCI 设备的 BAR-0 映射到虚拟地址空间,以便读取(并稍后修改)其内容。但是,当我映射它时,我收到以下错误:
Path to BAR-0: /sys/bus/pci/devices/0000:00:16.0/resource0
Error at line 42, file src/main.c (9) [Bad file descriptor]
我正在使用 Debian 9.1 32 位。我使用的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "../include/eeprom.h"
#include "../include/pci.h"
#include "../include/i2c.h"
#include "../include/types.h"
#define PRINT_ERROR \
do { \
fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
__LINE__, __FILE__, errno, strerror(errno)); exit(1);\
} while(0)
#define MAP_SIZE 4096
#define MAP_MASK (MAP_SIZE - 1)
int main (int argc, char* argv[]) {
uint32_t pci_dev;
void *mmap_base;
char *file = {"/sys/bus/pci/devices/0000:00:16.0/resource0"};
int i;
printf ("Path to BAR-0: %s\n", file);
//Open Bar-0 of PCI device
pci_dev = open (file, O_RDWR | O_SYNC);
if (pci_dev < 0)
{
PRINT_ERROR;
}
//Map BAR-0 from physical memory to virtual address space
mmap_base = mmap (NULL, MAP_SIZE, PROT_WRITE, MAP_SHARED, pci_dev, 0);
if (mmap_base == (void *)-1 || mmap_base == NULL) //error here
{
PRINT_ERROR;
}
printf ("Mapped on address %p of size %d Byte\n", mmap_base, MAP_SIZE);
return 0;
}
我已经可以说,我删除了设备使用的内核模块,所以这不是问题。
有人可以帮助我吗?提前致谢。
解决方案
我在学习 Linux Kernal 编程时遇到了类似的问题。以超级用户权限运行程序对我有用。
推荐阅读
- amazon-web-services - 无服务器——如何将 S3 存储桶名称作为环境变量传递给我的应用程序
- android - 如何在 android 代码中运行特定的 adb 命令?我有权限问题
- c# - C# 为不可序列化的属性生成 XML
- javascript - 修复 CORS 错误而不禁用 chrome 中的安全性
- installation - 尝试构建安装程序时出现“msadox28.tlb 文件受 Windows 系统文件保护”错误
- sql - Postgres:用于记录目的的数据库信息
- pyspark - 如何展平每个 id 包含多行的 pyspark 数据帧?
- ruby-on-rails - Adding external js files on Rails 6
- html - pytest:错误:无法识别的参数:--html=report.html
- python - 用 Python 重写 .txt 中的单个单词