3

我写了这个:

#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

如果我的程序有任何错误?

4

5 回答 5

2

你应该有这样的东西

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

于 2012-04-28T09:10:28.747 回答
2

是的,有问题。你的使用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);
于 2012-04-28T09:12:33.873 回答
1

也许这有帮助?

http://forums.freescale.com/t5/Other-Microcontrollers/Can-t-write-new-uboot-to-mtd0-in-linux-on-MPC8313E-RDB/td-p/34727

这一切都必须处理访问权限。

正如 Jakub 和 Mat 所说,检查每个 API 调用的错误代码。

于 2012-04-28T09:11:35.540 回答
1

您可能必须写一整页,而不仅仅是 4 个字节。

dmesg您可以通过在 shell 中键入命令来确认这一点。然后您应该看到以下内核消息:

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, ...

希望这可以帮助。

于 2015-08-20T16:34:31.347 回答
0

问题出在这一行:

if (write(fd, &buf, 4) < 0) {

写调用的第二个参数必须是一个指针,“buf”已经是一个指针,用“&”引用它,你会得到一个指向错误指针的指针:正确的调用是:

if (write(fd, (void*)buf, 4) < 0) {
于 2013-05-16T08:50:32.940 回答