Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a shared memory using Haskell's mmap library?

Tags:

haskell

On C, I can create a shared memory object with:

int fd = shm_open("/object", O_RDWR | O_CREAT, 0777);

I can also read from that memory using mmap:

int* addr = mmap(0, sizeof(*addr), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

But how do I access that data from Haskell?

import System.Posix.SharedMem
import System.IO.MMap

main = do
    fd <- shmOpen "/bolts" (ShmOpenFlags False False False False) 0777

    -- Obviously doesn't make sense, mmapFileByteString 
    -- requires a file path that I don't have!
    addr <- mmapFileByteString "/bolts" Nothing

    print addr
like image 988
MaiaVictor Avatar asked May 25 '15 22:05

MaiaVictor


1 Answers

It appears that the mmap package you are using does not support this functionality. However, the good news is that what you want is not that hard to implement. One approach is just to create a raw FFI binding for mmap, call mmap yourself, and then use packCStringLen to convert the pointer to a ByteString.

foreign import ccall "mmap" mmap
  :: Ptr () -> CSize -> CInt -> CInt-> CInt-> Int64 -> IO (Ptr ())

As another option, if you don't want your own FFI binding, the bindings-posix package will provide this for you as c'mmap.

like image 92
user3188445 Avatar answered Oct 07 '22 17:10

user3188445