How to create a virtual file in linux (or block device) (through code, C/++ or Python) that I can hook into read/write/etc?

116 views Asked by At

Question

I've found similar questions on SO, but none of them answer the question or at least not in a relevant way.

Is it possible to have a file appear anywhere (in the FS, under /dev whatever), such that anybody can access it as if it were a file (or ideally a block device), but such that every read/write/access of that file is hookable so that I can catch the accesses, be it in C/++ or in python?

I'm aware of FUSE & VFS, but as I understand, both are for creating/emulating an entire file system, not just a single file or block-device.

I also see make-dev & mknod being passed around, but nobody explains what you can actually do with mknod after "creating" the device node itself. How do I hook into accesses on that virtual node?

Basically, I need to re-route the accesses over a stream/socket, but it has to look/appear as a file, not a stream/socket, because those aren't seekable.

ANSWER

Just use FUSE. It actually innately supports the very trivial process of hooking into a single file, and is supported in C/++ & Python. I'll upload a python example soon. Instead of creating/using a folder as a mountpoint, you use an empty file instead. Upon mounting, the file then has whatever size/contents you want it to, and it is read/writable, and each access triggers one of your fuse callbacks, which is perfect. you can even implement custom ioctl to make it look like a block device. Then on every access, your callbacks are always passed the same path as a target, which is "/", but that doesn't matter anyways since you are dealing with a single file anyways so you don't need it.

0

There are 0 answers