ZBLOG

怎么监控文件被哪些进程修改了 golang

要监控文件被哪些进程修改了,您可以使用Golang中的os包和fsnotify包来实现。下面是一个简单的示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "github.com/fsnotify/fsnotify"
  7. )
  8. func main() {
  9. filePath := "/path/to/your/file.txt"
  10. watcher, err := fsnotify.NewWatcher()
  11. if err != nil {
  12. fmt.Println("Failed to create watcher:", err)
  13. return
  14. }
  15. defer watcher.Close()
  16. err = watcher.Add(filepath.Dir(filePath))
  17. if err != nil {
  18. fmt.Println("Failed to add directory to the watcher:", err)
  19. return
  20. }
  21. done := make(chan bool)
  22. go func() {
  23. for {
  24. select {
  25. case event, ok := <-watcher.Events:
  26. if !ok {
  27. return
  28. }
  29. if event.Name == filePath && (event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Chmod == fsnotify.Chmod) {
  30. processes, err := processesWithFileOpen(filePath)
  31. if err != nil {
  32. fmt.Println("Failed to get processes:", err)
  33. } else {
  34. fmt.Printf("File %s modified by processes: %v\n", filePath, processes)
  35. }
  36. }
  37. case err, ok := <-watcher.Errors:
  38. if !ok {
  39. return
  40. }
  41. fmt.Println("Error occurred:", err)
  42. }
  43. }
  44. }()
  45. fmt.Println("Monitoring changes to file:", filePath)
  46. <-done
  47. }
  48. // 获取打开指定文件的进程列表
  49. func processesWithFileOpen(filePath string) ([]string, error) {
  50. processes := []string{}
  51. fileInfo, err := os.Stat(filePath)
  52. if err != nil {
  53. return nil, err
  54. }
  55. fileInode := fileInfo.Sys().(*syscall.Stat_t).Ino
  56. processesData, err := ioutil.ReadFile("/proc/net/unix")
  57. if err != nil {
  58. return nil, err
  59. }
  60. lines := strings.Split(string(processesData), "\n")
  61. for _, line := range lines {
  62. fields := strings.Fields(line)
  63. if len(fields) >= 9 && fields[8] == filePath {
  64. pid, _ := strconv.Atoi(fields[6])
  65. cmdlineBytes, _ := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
  66. cmdline := string(bytes.Replace(cmdlineBytes, []byte{0}, []byte{' '}, -1))
  67. processes = append(processes, fmt.Sprintf("%d: %s", pid, cmdline))
  68. }
  69. }
  70. return processes, nil
  71. }

这个代码片段使用了fsnotify包来监视指定文件所在目录的变化,并在文件被修改时打印出正在访问该文件的进程列表。

请注意,为了获取打开指定文件的进程列表,代码中使用了读取 /proc/net/unix 文件和相应进程的命令行参数。此方法依赖于Linux系统下的特定路径和接口,并且需要足够的权限才能执行。请确保您具备适当的权限以及对应用程序环境的理解。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=18355

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?