[英]why does ioctl return “bad address”
我使用下面的代碼從嵌入式電路板的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 <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#include <errno.h>
static uint16_t delay;
int main(int argc,char *argv[]){
msg_send(254); //the message that I want to send decimal "254"
return 0;
}
void msg_send(int msg){
int fd;
int ret = 0;
fd = open("/dev/spidev32766.1", O_RDWR); //ls /dev outputs spidev32766.1
if(fd < 0){
fprintf(stderr, "errno:%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
結構的地址顯然是有效的,因此問題必須與其中一個成員有關。
根據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緩沖區指向該字符串並相應地設置長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.