go4.org@v0.0.0-20230225012048-214862532bf5/lock/lock_unix.go (about)

     1  // +build linux darwin freebsd openbsd netbsd dragonfly solaris
     2  // +build !appengine
     3  
     4  /*
     5  Copyright 2013 The Go Authors
     6  
     7  Licensed under the Apache License, Version 2.0 (the "License");
     8  you may not use this file except in compliance with the License.
     9  You may obtain a copy of the License at
    10  
    11       http://www.apache.org/licenses/LICENSE-2.0
    12  
    13  Unless required by applicable law or agreed to in writing, software
    14  distributed under the License is distributed on an "AS IS" BASIS,
    15  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    16  See the License for the specific language governing permissions and
    17  limitations under the License.
    18  */
    19  
    20  package lock
    21  
    22  import (
    23  	"fmt"
    24  	"io"
    25  	"os"
    26  
    27  	"golang.org/x/sys/unix"
    28  )
    29  
    30  func init() {
    31  	lockFn = lockFcntl
    32  }
    33  
    34  func lockFcntl(name string) (io.Closer, error) {
    35  	fi, err := os.Stat(name)
    36  	if err == nil && fi.Size() > 0 {
    37  		return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name)
    38  	}
    39  
    40  	f, err := os.Create(name)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("Lock Create of %s failed: %v", name, err)
    43  	}
    44  
    45  	err = unix.FcntlFlock(f.Fd(), unix.F_SETLK, &unix.Flock_t{
    46  		Type:   unix.F_WRLCK,
    47  		Whence: int16(os.SEEK_SET),
    48  		Start:  0,
    49  		Len:    0, // 0 means to lock the entire file.
    50  		Pid:    0, // only used by F_GETLK
    51  	})
    52  
    53  	if err != nil {
    54  		f.Close()
    55  		return nil, fmt.Errorf("Lock FcntlFlock of %s failed: %v", name, err)
    56  	}
    57  	return &unlocker{f: f, abs: name}, nil
    58  }