Golang flock filelocking throwing panic: runtime error: invalid memory address or nil pointer dereference

Golang flock filelocking throwing panic: runtime error: invalid memory address or nil pointer dereference

我有一个go程序可以修改我的配置文件。我试图从 main() 函数中创建一个文件锁,但它抛出了一个 panic: runtime error: invalid memory address or nil pointer dereference 错误。没有锁,程序按预期工作正常。抛出异常的代码是

lockProgram, err := os.Create("/var/.daemon.lock")
defer lockProgram.Close()
CheckForError(err)
GetLock(lockProgram, syscall.LOCK_EX)
defer UngetLock(lockProgram)

//这个在单独的包里

func CheckForError(e error) {
    if e != nil {
        Error.Println(e)
        panic(e)
    }
}

func GetLock(file *os.File, locktype int )  {
    fmt.Println("Acquiring lock on ", file.Name())
    syscall.Flock(int(file.Fd()), locktype)
    fmt.Println("Acquired filelock on ", file.Name())
}
func UngetLock(file *os.File)  {
    syscall.Flock(int(file.Fd()), syscall.LOCK_UN);
}

当我在我的配置文件上调用它时,同样的 flock 正在工作,但来自不同的包,而不是主包,但是当我尝试从主包中放置锁时抛出相同的错误。请帮助我找出我在这里做错了什么。

如果在创建锁时发生错误,lockProgram 将是 nil。这将导致对 lockProgram.Close() 的后续(延迟)调用失败。

请注意,当您恐慌时(例如在您的 CheckForError 函数中),延迟的方法调用仍将被执行。这在 this blog article 中有详细解释(重点是我的):

Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes.

解决方案:先检查错误,然后推迟 Close() 调用:

lockProgram, err := os.Create("/var/.daemon.lock")
CheckForError(err)
defer lockProgram.Close()