file - Golang 群文件锁定抛出 panic : runtime error: invalid memory address or nil pointer dereference

标签 file go flock filelock panic

我有一个 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() 的后续(延迟)调用失败。

请注意,当您 panic 时(例如在您的 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()

关于file - Golang 群文件锁定抛出 panic : runtime error: invalid memory address or nil pointer dereference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710460/

相关文章:

将文件转换为 C 中的二进制缓冲区?

go - 为什么指针在这个 Go 程序中失去了它的值(value)

c - 如何在 C 中使用 fork 写入和读取文件

java - 遍历Java中的所有文件

python - 将数据文件解析为二维数组

mysql - App Engine 中的 GoLang 动态 SQL 查询

database - Golang 测试,调用数据库 Prepare 应该会失败,但实际上并没有

linux - 如何在flock中使用文件描述符变量?

c - flock(),然后是 fgets() : low-level locks,,然后是 stdio 读/写库函数。是否可以?

linux - 在 Linux 中每台打印机列出 100 个文件