File Lock Guard Critical Section

Use file locks for cross-process critical sections with flock in Go applications safely.

GoSecurity Boundaries

Code

gosnippet
16 lines
package main
import ("os";"syscall";"fmt")
func withFileLock(path string, fn func() error) error {
    f, err := os.Create(path)
    if err != nil { return err }
    defer f.Close()
    if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { return err }
    defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
    return fn()
}
func main() {
    withFileLock("/tmp/app.lock", func() error {
        fmt.Println("critical section")
        return nil
    })
}

How it works

The working surface is the functions withFileLock and main — everything else is wiring.

err is inspected at 2 call sites before any result is trusted. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Watch out for

  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

The main signature reads func withFileLock(path string, fn func() error) error

Running the file prints labeled results such as critical section — each operation’s effect is visible in the output.

The demo flow inside main is withFileLock — run the file to see it end to end.

Key statements

func withFileLock(path string, fn func() error) error {
f, err := os.Create(path)
if err != nil { return err }
defer f.Close()
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { return err }
defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
return fn()
}
func main() {
withFileLock("/tmp/app.lock", func() error {
fmt.Println("critical section")
return nil
})
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
Through `error` values, not panics — the snippet checks `err != nil` at 2 sites.
What does File Lock Guard Critical Section print when run?
Invoke the file as-is — the `critical section` prefixes identify which step printed each line.