douqiang6448 2017-10-08 14:55
浏览 97

在Golang中将字节数组转换为syscall.InotifyEvent结构

I'm playing around with the inotify functionality in golang's syscall library. I'm able to setup the inotify functionality with InotifyInit, add a file to watch with InotifyAddWatch and detect file changes with the Read function. The problem that I'm having is that the Read function only reads into a byte array containing info about the inotify events. I'd like to convert/cast that byte array into an InotifyEvent structure so that I can access information about the inotify events properly

Below is what I have so far:

package main

import (
    "fmt"
    "syscall"
)

func main() {
    buff := make([]byte, 64)
    inotefd, err := syscall.InotifyInit()
    if err != nil {
        fmt.Println(err)
    }
    _, err = syscall.InotifyAddWatch(inotefd, "/home/me/foo", syscall.IN_MODIFY)
    if err != nil {
        fmt.Println(err)
    }

    for {
        n, err := syscall.Read(inotefd, buff)
        if err != nil {
            fmt.Println(err)
            return
        }

        if n < 0 {
            fmt.Println("Read Error")
            return
        }

        fmt.Printf("Buffer: %v
", buff)
        //can't cast []buff into InotifyEvent struct
        fmt.Printf("Cookie: %v
", buff[0:4])
        fmt.Printf("Len: %v
", buff[4:8])
        fmt.Printf("Mask: %v
", buff[8:12])
        fmt.Printf("Name: %v
", buff[12:13])
        fmt.Printf("Wd: %v
", buff[13:17])
    }
}

Thanks for your help !

  • 写回答

1条回答 默认 最新

  • dongmu3269 2017-10-08 16:16
    关注

    You can use the unsafe package for that:

        info := *((*syscall.InotifyEvent)(unsafe.Pointer(&buff[0])))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思