为什么ioctl会返回“糟糕的地址”

我使用下面的代码从嵌入式电路板的SPI端口输出数据(olimex imx233-micro – 它不是特定于电路板的问题).当我运行代码ioctl返回“坏地址”.我正在修改http://twilight.ponies.cz/spi-test.c上的代码,工作正常.谁能告诉我我做错了什么?

root@ubuntu:/home# gcc test.c -o test
test.c:20: warning: conflicting types for ‘msg_send’
test.c:16: note: prevIoUs implicit declaration of ‘msg_send’ was here
root@ubuntu:/home# ./test
errno:Bad address - cannot send SPI message
root@ubuntu:/home# uname -a
Linux ubuntu 3.7.1 #2 Sun Mar 17 03:49:39 CET 2013 armv5tejl GNU/Linux

码:

//test.c
#include dio.h>
#include etopt.h>
#include %s - FD Could be not opened\n ",strerror(errno));  
        exit(1);
        }

    struct spi_ioc_transfer tr = {
        .len = 1,.delay_usecs = delay,.speed_hz = 500000,//500 kHz
        .bits_per_word = 8,.tx_buf = msg,.rx_buf = 0,//half duplex
    };

    ret = ioctl(fd,SPI_IOC_MESSAGE(1),&tr);
    if (ret <1 ){
        fprintf(stderr,"errno:%s - cannot send SPI message\n ",strerror(errno));
    }
    close(fd);
}

谢谢!

最佳答案
错误消息“错误地址”来自错误代码EFAULT,当您将地址传递给内核时会发生这种情况,该内核不是进程虚拟地址空间中的有效虚拟地址. tr结构的地址显然是有效的,因此问题必须与其中一个成员有关.

根据definition of struct spi_ioc_transfer,.tx_buf和.rx_buf成员必须是指向用户空间缓冲区的指针,或者为null.您将.tx_buf设置为整数254,它不是有效的用户空间指针,因此这是坏地址的来源.

我不熟悉这个IOCTL,所以我最好的猜测是你需要用二进制来对数据进行低音.一种方法是这样做:

struct spi_ioc_transfer tr = {
    .len = sizeof(msg),// Length of rx and tx buffers
     ...
    .tx_buf = (u64)&msg,// Pointer to tx buffer
    ...
};

如果您需要将其作为ASCII发送,那么您应该使用诸如snprintf(3)之类的函数将整数转换为ASCII字符串,然后将TX缓冲区指向该字符串并相应地设置长度.

相关文章

Linux中的ARP防火墙主要用于防御ARP欺骗攻击,其效果取决于多...
insmod和modprobe加-f参数导致Invalid module format错误 这...
将ArchLinux安装到U盘 几个月前入门Arch的时候上网搜了不少安...
1、安装Apache。 1)执行如下命令,安装Apache服务及其扩展包...
一、先说一下用ansible批量采集机器信息的实现办法: 1、先把...
安装配置 1. 安装vsftpd 检查是否安装了vsftpd # rpm -qa | ...