Search code examples
linuxgreptmpfs

Treat tmpfs as a device for grep


I have to test my program, that it completely removes files with their contents from disk. To test that I do the following:

  1. Create a file with some known string inside.
  2. My program deletes the file.
  3. I search the string on the disk where the file was located. To do that I make grep consider the disk as a pile of raw data:
$ grep -a -o -c 'some_string_to_be_found' /dev/sda1

The test actually works as expected (finds the string if I delete the file manually, and doesn't if my program deletes it).

The problem is that the disk size may be big, so it would require a huge amount of time to complete the test. Also, the label for the disk may vary on different machines.

Therefore I think about how to use a virtual filesystem instead. Create a disk in RAM, using tmpfs:

pc:/mnt$ mkdir tmpfs
pc:/mnt$ chmod 777 tmpfs/
pc:/mnt$ mount -t tmpfs -o size=50M tmpfs /mnt/tmpfs/

create/fill/delete a file, and then try to find its content, using something like:

$ grep -a -o -c 'some_string_to_be_found' /dev/tmpfs

The problem is that it results in

grep: /dev/tmpfs: No such file or directory

So the question is: is it possible to use tmpfs as a device, or read the raw memory allocated for the virtual filesystem?


Solution

  • Although I haven't found a way how to treat tmpfs as a device, there is a way for solving my taks described above (may be useful sor someone).

    We will treat a file as a device. The algorithm is as follows:

    1. Create an empty file with specified size:

       # touch storage_file
       # truncate -s 10M storage_file
      
    2. Create a filesystem inside that file:

       # mkfs.ext4 storage_file
      
    3. Now we are able to create a device from that file and mount it as an ordinary disk:

       # losetup /dev/loop0 storage_file
       # mkdir /mnt/loopfs
       # mount -o loop /dev/loop0 /loopfs
      
    4. That's all. We're able to treat the file as a device. Create/delete arbitrary files/directories inside it. And grep through /dev/loop0 works as expected, w/o processing entire physical storage device, crawling inside the storage_file only.