[英]linux programming: write to device file
我写了这个:
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <mtd/mtd-user.h>
#include <errno.h>
int main( void )
{
int fd;
char buf[4]="abc";
fd = open("/dev/mtd0", O_RDWR);
lseek(fd, 1, SEEK_SET);
write(fd, &buf, 4);
close(fd);
perror("perror output:");
return 0;
}
文件/ dev / mtd0是使用nandsim内核模块创建的,然后运行
mtdinfo /dev/mtd0
得到了有意义的输出。运行我的程序后,它的输出:
perror output:: Invalid argument
如果我的程序有任何错误?
是的,有一个问题。 你使用perror()
是错误的。
在调用perror之前,您应首先检查系统调用是否表示存在问题。 手册页非常清楚:
Note that errno is undefined after a successful library call: this call
may well change this variable, even though it succeeds, for example
because it internally used some other library function that failed.
Thus, if a failing call is not immediately followed by a call to per‐
ror(), the value of errno should be saved.
您应该检查每个系统的返回代码,并且只有在它们失败时才调用perror。 像这样的东西:
fd = open("/dev/mtd0", O_RDWR);
if (fd < 0) {
perror("open: ");
return 1;
}
if (lseek(fd, 1, SEEK_SET) < 0) {
perror("lseek: ");
return 1;
}
if (write(fd, &buf, 4) < 0) {
perror("write: ");
return 1;
}
close(fd);
你应该有这样的东西
if(-1 == write(fd, &buf, 4)){
perror("perror output:");
}
close(fd);
因为perror显示最后一个错误。
http://www.cplusplus.com/reference/clibrary/cstdio/perror/
更多关于perror http://www.java-samples.com/showtutorial.php?tutorialid=597
也许这有帮助吗?
这一切都必须处理访问权限。
正如Jakub和Mat所说,检查每个API调用的错误代码。
您可能必须编写整个页面而不仅仅是4个字节。
您可以通过在shell中键入命令dmesg
来确认这一点。 然后你应该看到以下内核消息:
nand_do_write_ops:尝试写入不是页面对齐的数据
然后将代码替换为在mtd中写入:
char buf[2048]="abcdefghij"; //Ajust size according to
//mtd_info.writesize
mtd_info_t mtd_info; // the MTD structure
if (ioctl(fd, MEMGETINFO, &mtd_info) != 0) {... // get the device info
memset(buf+10, 0xff, mtd_info.writesize - 10); //Complete buf with 0xff's
if (write(fd, &buf, mtd_info.writesize) < 0) {... // write page
还要考虑在写入之前检查坏块( ioctl(fd, MEMGETBADBLOCK, ...
)和擦除块( ioctl(fd, MEMERASE, ...
))。
希望这可以帮助。
问题出在这一行:
if (write(fd, &buf, 4) < 0) {
写调用的第二个参数必须是一个指针,“buf”已经是一个指针,用“&”引用它你得到一个指向错误指针的指针:正确的调用是:
if (write(fd, (void*)buf, 4) < 0) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.