2

I want to create a temporary file in memory, without it writing to disk, that can be opened for reading using CreateFile from other processes as if it was a normal file.

Is this possible or do I have to write it to the disk?

man
  • 145
  • 2
  • 11
  • http://stackoverflow.com/questions/5135854/make-a-file-pointer-read-write-to-an-in-memory-location – Jacques de Hooge Oct 15 '16 at 16:31
  • @AmericanPatriot Since I am working with the Windows API, also known as WinAPI. – man Oct 15 '16 at 16:34
  • @JacquesdeHooge `fmemopen` doesn't seem to be available on Windows. – man Oct 15 '16 at 16:37
  • Yeah, POSIX is like that. – user4581301 Oct 15 '16 at 16:39
  • @JacquesdeHooge `fmemopen` returns `FILE*` mapped to the process memory space - you cannot share that across multiple processes. For sharing you need something accessible by path in FS - known to all. – c-smile Oct 15 '16 at 16:47
  • Search the internet for "memory mapped file". This is a platform specific topic, so you should include your platform name in the query. – Thomas Matthews Oct 15 '16 at 16:54
  • You can certainly do it with a memory mapped file but there's always the possibility it will hit the disk if the memory system needs to swap it out. – David Heffernan Oct 15 '16 at 17:21
  • Typical technology for sharing memory between processes is [Named Shared Memory](https://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx). However you won't be able to use CreateFile to access it. If CreateFile is not a hard requirement, I would suggest looking into shared memory segment. – seva titov Oct 15 '16 at 18:40
  • The question sounds a lot, like you are asking about your solution rather than your issue. What problem are you really trying to solve? – IInspectable Oct 16 '16 at 11:06

2 Answers2

2

What you are asking for cannot generally be done with CreateFile() (unless you go the RAMdisk approach), but it can be done using CreateFileMapping() and MapViewOfFile() instead. The mapping object can be assigned a name so it can be shared across process boundaries, and then multiple processes can have their own views open to it as needed.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

CreateFile takes file path as a parameter. For other processes to be able to open it that file location shall be mapped to one of devices existing in the system.

One of such devices can be a RAM disk/device where you can create files without writing them to physical disk (memory swapping aside). But that requires installation and activation of such a (virtual) device.

If you just need to share memory between processes then take a look on shmem implementation for example.

c-smile
  • 26,734
  • 7
  • 59
  • 86