java - Java中对/dev/raw/raw1的RandomAccessFile访问

标签 java linux

我创建了一个原始设备:

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/

相关文章:

linux - 从 linux 命令行停止 linux aws 实例

c++ - C++ select() 函数如何在 Unix 操作系统中工作?

java - 如何在 Java 中同步未同步的集合

java - 在 Android Studio 上将模块或项目作为库导入

java - 使用 ActiveMQ 5,是否可以在内存和网络连接中配置代理?

linux - 尝试在 Mandriva 上构建 OS161 时出现 "bmake: no system rules (sys.mk)"

java - 包装对象和平等

java - Eclipse 内容支持不适用于 Groovy 文件中的 Java 对象

linux - 如何在 Linux 内核级别限制特权用户访问?

Linux 上的 C++ : Setting up socket & packets for minimum RTP stream latency