ZBLOG

加上最后被什么进程修改的信息

要获取最后修改文件的进程信息,你可以使用系统调用来实现。在Linux上,可以使用inotify机制来监视文件系统事件,并获取相关信息。

下面是一个修改后的示例代码,包括了获取最后修改文件的进程信息:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "os/exec"
  7. "time"
  8. "github.com/fsnotify/fsnotify"
  9. )
  10. func monitorFile(filename string) {
  11. watcher, err := fsnotify.NewWatcher()
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. defer watcher.Close()
  16. err = watcher.Add(filename)
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. for {
  21. select {
  22. case event, ok := <-watcher.Events:
  23. if !ok {
  24. return
  25. }
  26. if event.Op&fsnotify.Write == fsnotify.Write {
  27. fmt.Println("File modified:", event.Name)
  28. out, err := exec.Command("lsof", "-b", "-n", "-t", "--", event.Name).Output()
  29. if err != nil {
  30. log.Fatal(err)
  31. }
  32. pid := string(out[:len(out)-1])
  33. out, err = exec.Command("ps", "-p", pid, "-o", "comm=").Output()
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. processName := string(out[:len(out)-1])
  38. fmt.Println("Last modified by process:", processName)
  39. }
  40. case err, ok := <-watcher.Errors:
  41. if !ok {
  42. return
  43. }
  44. log.Println("error:", err)
  45. }
  46. }
  47. }
  48. func main() {
  49. filename := "test.txt" // 需要监控的文件名
  50. go monitorFile(filename)
  51. // 主程序可继续执行其他任务
  52. select {}
  53. }

在修改后的monitorFile函数中,我们添加了对fsnotify.Write事件的处理。当文件被修改时,会打印相应的信息,并通过执行lsof命令获取最后修改文件的进程ID。然后,使用ps命令根据进程ID获取进程名称,并将其打印出来。

请注意,你需要确保操作系统上已安装并配置了正确的命令行工具(如lsofps),以便能够在Go代码中调用它们。此外,请根据你的实际需求进行适当的错误处理和资源管理。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?