Direct access to hard disk with no FS from C program on Linux

穿精又带淫゛_ 提交于 2019-11-26 14:01:19

问题


I want to access the whole hard disk directly from a C program. There's no FS on it and never's gonna be one.

I just want to open /dev/sda (for example) and do I/O at the block/sector level of the disk.

I'm planning to write some programs for learning C programming in the Linux environment (I know C language, Python, Perl and Java) but lack confidence with the Linux environment.

For my learning purposes I'm thinking about playing with kyoto-cabinet and saving the value corresponding to the computed hash directly into a "block/sector" of the hard disk, recording the pair: "hash, block/sector reference" into a kyoto-cabinet hash database file.

I don't know if this is feasible using standard C I/O functions or otherwise I'd have to write a "device driver" or something like...


回答1:


As mentioned elsewhere, under *NIX systems, block devices like /dev/sda can be accessed as plain files. Note that if file system is mounted from the device, opening it as file for writing would fail.

If you want to play with block devices, I would advise to first use the loop device, which presents a plain file as a block device. For example:

dd if=/dev/zero of=./loop_file_10MB bs=1024 count=10K
losetup /dev/loop0 $PWD/loop_file_10MB

After that, /dev/loop0 would behave as if it was a block device, but all information written would be stored in the file.




回答2:


As device files for drives (e.g. /dev/sda) are block devices, this means you can open, seek and use the file almost like a normal file.




回答3:


Yes, as others have noted, you can simply open the block device.

However, it's a really good idea to do IO (writes anyway) on block boundaries and whole blocks. You can use something like pread() and pwrite() to do these IO, or mmap some or all of the device.

There are a bunch of ioctls which can be used, see "man sd" for some more info. They don't seem to all be documented in the same place.

In linux/fs.h BLKROSET and a bunch of other ioctls are defined, you have to look around to find out how to use them. You can do useful things like find out how big the device is, and what the block size is.

The source code of the util-linux-ng package is your friend, it contains examples.



来源:https://stackoverflow.com/questions/3520459/direct-access-to-hard-disk-with-no-fs-from-c-program-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!