我创建了一个原始设备:
raw /dev/raw/raw1 /dev/sda3
我无法在 java 中使用 RandomAccessFile
访问它。
File ssd=new File("/dev/raw/raw1");
RandomAccessFile randomaccess=new RandomAccessFile(ssd, "rw");
System.out.println("randomaccess file created");
randomaccess.write((byte)1);
System.out.println("wrote to file");
randomaccess.close();
当我使用 sudo 运行它时,我有适当的权限,但它失败了:
randomacces file created
java.io.IOException: Invalid argument
at java.io.RandomAccessFile.write0(Native Method)
at java.io.RandomAccessFile.write(RandomAccessFile.java:489)
at Randomacces.main(Randomacces.java:23)
是不是因为 RandomAccessFile
需要一个 block 设备,但原始设备的行为像一个字符设备?
如果我使用:
File ssd=new File("/dev/sda3");
它运行没有问题,但我想禁用页面缓存。有什么方法可以让它工作,还是我需要编写自己的设备驱动程序?
最佳答案
来自raw(8) man page :
Because raw I/O involves direct hardware access to a process's memory, a few extra restrictions must be observed. All I/Os must be correctly aligned in memory and on disk: they must start at a sector offset on disk, they must be an exact number of sectors long, and the data buffer in virtual memory must also be aligned to a multiple of the sector size. The sector size is 512 bytes for most devices.
如果你不遵守这些限制,低级 write(2) system call将返回 EINVAL(无效参数)。
鉴于 Java 和操作系统之间存在许多抽象层,您将很难让 Java 发出大小正确且对齐的写入调用。最后一个要求特别棘手:“虚拟内存中的数据缓冲区也必须对齐到扇区大小的倍数”。没有保证,但使用 java.nio
类而不是 java.io
可能会更好。
关于java - Java中对/dev/raw/raw1的RandomAccessFile访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333924/