writen 和 readn函数实现

C语言代码

// 从描述符 fd 读取 n 个字节
ssize_t readn(int fd, void *vptr, size_t n)
{
    size_t nleft;
    ssize_t nread;
    char *ptr;

    ptr = vptr;
    nleft = n;
    while (nleft > 0){
        if ( (nread = read(fd, ptr, nleft)) < 0){
            if (errno == EINTR)
                nread = 0;  //再次调用read()
            else
                return -1;
        } else if (nread 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PCIE(Peripheral Component Interconnect Express)是一种高速的外部总线接口,用于连接计算机主机和外部设备,例如显卡、网卡、存储设备等。在使用PCIE接口进行数据传输时,需要使用读写函数进行数据读写操作。 下面是两个示例: 1. 读取PCIE设备的寄存器值 ```c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/mman.h> #include <fcntl.h> #define PCIE_BAR0_BASE_ADDR 0x40000000 // PCIE设备的BAR0基地址 #define REG_ADDR 0x10 // 寄存器的偏移地址 int main() { int fd; uint32_t *base_addr; uint32_t reg_val; fd = open("/dev/mem", O_RDWR | O_SYNC); if (fd == -1) { perror("open"); exit(EXIT_FAILURE); } base_addr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, PCIE_BAR0_BASE_ADDR); if (base_addr == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); } reg_val = *(base_addr + REG_ADDR/4); printf("Register value is: %x\n", reg_val); munmap(base_addr, 4096); close(fd); return 0; } ``` 2. 向PCIE设备的寄存器写入数据 ```c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/mman.h> #include <fcntl.h> #define PCIE_BAR0_BASE_ADDR 0x40000000 // PCIE设备的BAR0基地址 #define REG_ADDR 0x10 // 寄存器的偏移地址 int main() { int fd; uint32_t *base_addr; uint32_t data = 0x12345678; fd = open("/dev/mem", O_RDWR | O_SYNC); if (fd == -1) { perror("open"); exit(EXIT_FAILURE); } base_addr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, PCIE_BAR0_BASE_ADDR); if (base_addr == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); } *(base_addr + REG_ADDR/4) = data; printf("Data is written to register.\n"); munmap(base_addr, 4096); close(fd); return 0; } ``` 需要注意的是,对PCIE设备的读写操作需要在合适的权限下进行,例如需要root权限。此外,PCIE设备的寄存器偏移地址和数据类型需要根据具体的设备文档进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值