github.com/apptainer/singularity@v3.1.1+incompatible/pkg/util/fs/lock/lock.go (about)

     1  // Copyright (c) 2018, Sylabs Inc. All rights reserved.
     2  // This software is licensed under a 3-clause BSD license. Please consult the
     3  // LICENSE file distributed with the sources of this project regarding your
     4  // rights to use or distribute this software.
     5  
     6  package lock
     7  
     8  import (
     9  	"os"
    10  	"syscall"
    11  )
    12  
    13  // Exclusive applies an exclusive lock on path
    14  func Exclusive(path string) (fd int, err error) {
    15  	fd, err = syscall.Open(path, os.O_RDONLY, 0)
    16  	if err != nil {
    17  		return fd, err
    18  	}
    19  	err = syscall.Flock(fd, syscall.LOCK_EX)
    20  	if err != nil {
    21  		syscall.Close(fd)
    22  		return fd, err
    23  	}
    24  	return fd, nil
    25  }
    26  
    27  // Release removes a lock on path referenced by fd
    28  func Release(fd int) error {
    29  	defer syscall.Close(fd)
    30  	if err := syscall.Flock(fd, syscall.LOCK_UN); err != nil {
    31  		return err
    32  	}
    33  	return nil
    34  }