chenshijun
2020-03-31 6d9477b720f2ba12b85b3007e2a07777eca9e01b
shmwrap.go
@@ -10,13 +10,14 @@
// NewBlock shm block with size
func NewBlock(size int, key int) ([]byte, int, error) {
    id, err := shm.Get(key, size, shm.IPC_CREAT|0666)
    fmt.Println("Get:", id, err)
    if err != nil || id == -1 {
        fmt.Printf("NewBlock Get:%x, %v\n", key, err)
        return nil, -1, err
    }
    data, err2 := shm.At(id, 0, 0)
    if err2 != nil {
        fmt.Printf("NewBlock At:%x, %v\n", key, err2)
        return nil, -1, err2
    }
@@ -26,13 +27,14 @@
// AttachBlock attach exist shm
func AttachBlock(key int) ([]byte, int, error) {
    id, err := shm.Get(key, 0, 0)
    fmt.Println("Get:", id, err)
    if err != nil || id == -1 { //no exist
        fmt.Printf("AttachBlock Get:%x, %v\n", key, err)
        return nil, -1, err
    }
    data, err2 := shm.At(id, 0, 0)
    if err2 != nil {
        fmt.Printf("AttachBlock Get:%x, %v\n", key, err2)
        return nil, -1, err2
    }
@@ -50,7 +52,6 @@
// context for quit
func CreateRawShm(ctx context.Context, size int, key int) ([]byte, int) {
    data, id, err := AttachBlock(key)
    fmt.Println("err:", err)
    if err != nil {
    loopB:
        for {
@@ -60,8 +61,6 @@
            default:
                if err == nil {
                    break loopB
                } else {
                    fmt.Println("createShm error:", err)
                }
                time.Sleep(time.Millisecond)
                data, id, err = NewBlock(size, key)
@@ -83,8 +82,6 @@
            default:
                if err == nil {
                    break loopB
                } else {
                    fmt.Println("createShm error:", err)
                }
                time.Sleep(time.Millisecond)
                data, id, err = AttachBlock(key)
@@ -139,3 +136,58 @@
func RemoveShmID(id int) error {
   return shm.Rm(id)
}
// RemoveShmKey Remove shmkey
func RemoveShmKey(shmkey int) error {
    _, id, err := AttachBlock(shmkey)
    if err != nil {
        return err
    } else {
        return shm.Rm(id)
    }
}
// DetachShmKey detach shmkey
func DetachShmKey(shmkey int) error {
    d, _, err := AttachBlock(shmkey)
    if err != nil {
        return err
    } else {
        return Detach(d)
    }
}
// DetachAndRemoveShmKey detach and Remove shmkey
func DetachAndRemoveShmKey(shmkey int) error {
    d, id, err := AttachBlock(shmkey)
    if err != nil {
        return err
    } else {
        Detach(d)
        return shm.Rm(id)
    }
}
func ShmAttachNum(shmId int) (int,error) {
    var idDs shm.IdDs
    _, err := shm.Ctl(shmId, shm.IPC_STAT, &idDs)
    if err != nil {
        return 0, err
    }
    return int(idDs.Nattch), nil
}
func ForceRemoveShm(data []byte, shmId int) error {
    count, err := ShmAttachNum(shmId)
    if err != nil{
        return err
    }else{
        for i:=0; i < count; i++{
            Detach(data)
        }
    }
    RemoveShmID(shmId)
    return nil
}