【问题标题】:convert byte array into syscall.InotifyEvent struct in Golang将字节数组转换为 Golang 中的 syscall.InotifyEvent 结构
【发布时间】:2017-10-08 14:55:55
【问题描述】:

我正在使用 golang 的系统调用库中的 inotify 功能。我可以使用InotifyInit 设置inotify 功能,使用InotifyAddWatch 添加要监视的文件,并使用Read 功能检测文件更改。我遇到的问题是 Read 函数仅读取到包含有关 inotify 事件信息的字节数组。我想将该字节数组转换/转换为 InotifyEvent 结构,以便我可以正确访问有关 inotify 事件的信息

以下是我目前所拥有的:

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\n", buff)
        //can't cast []buff into InotifyEvent struct
        fmt.Printf("Cookie: %v\n", buff[0:4])
        fmt.Printf("Len: %v\n", buff[4:8])
        fmt.Printf("Mask: %v\n", buff[8:12])
        fmt.Printf("Name: %v\n", buff[12:13])
        fmt.Printf("Wd: %v\n", buff[13:17])
    }
}

感谢您的帮助!

【问题讨论】:

    标签: go inotify


    【解决方案1】:

    您可以为此使用unsafe 包:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多