Documentation
¶
Overview ¶
Package filelock provides cross-platform advisory file locks for single-instance services, registries, and other on-disk critical sections.
Use Acquire for a held lock with an explicit release callback. By default acquisition is non-blocking; combine Blocking and WritePID for daemon locks. Pass a context.Context to cancel blocking waits.
Use With or WithSidecar for scoped, callback-style exclusive access.
Examples ¶
release, err := filelock.Acquire(context.Background(), "/var/run/myapp/daemon.lock", filelock.WritePID())
if err != nil {
return err
}
defer release()
err = filelock.WithSidecar(context.Background(), "/var/lib/myapp/state.json", filelock.DefaultSidecar, func() error {
return updateState()
})
Index ¶
- Constants
- Variables
- func Acquire(ctx context.Context, lockPath string, opts ...Option) (release func(), err error)
- func With(ctx context.Context, lockPath string, fn func() error, opts ...Option) error
- func WithSidecar(ctx context.Context, basePath, sidecar string, fn func() error, opts ...Option) error
- type Option
Constants ¶
const DefaultFileMode = 0o644
DefaultFileMode is the mode used when creating lock files.
const DefaultSidecar = ".lock"
DefaultSidecar is appended to a base path by WithSidecar.
const O_RDWR_CREATE = os.O_CREATE | os.O_RDWR
O_RDWR_CREATE is the open flag set used for lock files.
Variables ¶
var ErrBusy = errors.New("filelock: busy")
ErrBusy is returned when a non-blocking lock attempt finds the file already locked.
Functions ¶
func Acquire ¶
Acquire takes an exclusive lock at lockPath until release is called. By default acquisition is non-blocking; pass Blocking to wait, or WritePID to record the holder process id in the lock file. Context cancellation stops a blocking wait.
func With ¶
With runs fn while holding an exclusive lock at lockPath. Acquisition is blocking unless NonBlocking is passed. Context cancellation stops a blocking wait.
func WithSidecar ¶
func WithSidecar(ctx context.Context, basePath, sidecar string, fn func() error, opts ...Option) error
WithSidecar runs fn while holding an exclusive lock at basePath+sidecar. When sidecar is empty, DefaultSidecar is used.
Types ¶
type Option ¶
type Option func(*config)
Option configures Acquire and With.
func NonBlocking ¶
func NonBlocking() Option
NonBlocking makes Acquire return ErrBusy instead of waiting when the lock is held. With is blocking by default; pass NonBlocking to try once and return ErrBusy.