2017-10-08 152 views
1

我正在玩golang的syscall库中的inotify功能。我可以使用InotifyInit设置inotify功能,添加一个文件以便与InotifyAddWatch一起观看,并使用Read函数检测文件更改。我遇到的问题是Read函数只读入包含inotify事件信息的字节数组。我想转换/施放该字节数组到InotifyEvent结构,使我可以访问有关inotify事件信息正确将字节数组转换为Golang中的syscall.InotifyEvent结构

下面是我到目前为止有:

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]) 
    } 
} 

感谢您的帮助!

回答

1

可以使用unsafe包为:

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