github.com/fengyoulin/shm@v0.0.0-20200305015033-287e184bdf0a/mapping/unix.go (about)

     1  // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
     2  
     3  package mapping
     4  
     5  import (
     6  	"golang.org/x/sys/unix"
     7  	"os"
     8  )
     9  
    10  // Mapping of a file
    11  type Mapping struct {
    12  	data []byte
    13  }
    14  
    15  // Bytes return mapped memory
    16  func (m *Mapping) Bytes() (b []byte) {
    17  	return m.data
    18  }
    19  
    20  // Create a mapping from a file
    21  func Create(file *os.File) (m *Mapping, err error) {
    22  	info, err := file.Stat()
    23  	if err != nil {
    24  		return
    25  	}
    26  	size := info.Size()
    27  	data, err := unix.Mmap(int(file.Fd()), 0, int(size), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED)
    28  	if err != nil {
    29  		return
    30  	}
    31  	m = &Mapping{
    32  		data: data,
    33  	}
    34  	return
    35  }
    36  
    37  // Close a mapping
    38  func (m *Mapping) Close() (err error) {
    39  	return unix.Munmap(m.data)
    40  }