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

     1  /*
     2  Copyright 2013 The Go Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package lock
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"sync"
    24  
    25  	"golang.org/x/sys/windows"
    26  )
    27  
    28  func init() {
    29  	lockFn = lockWindows
    30  }
    31  
    32  type winUnlocker struct {
    33  	h   windows.Handle
    34  	abs string
    35  	// err holds the error returned by Close.
    36  	err error
    37  	// once guards the close method call.
    38  	once sync.Once
    39  }
    40  
    41  func (u *winUnlocker) Close() error {
    42  	u.once.Do(u.close)
    43  	return u.err
    44  }
    45  
    46  func (u *winUnlocker) close() {
    47  	lockmu.Lock()
    48  	defer lockmu.Unlock()
    49  	delete(locked, u.abs)
    50  
    51  	u.err = windows.CloseHandle(u.h)
    52  }
    53  
    54  func lockWindows(name string) (io.Closer, error) {
    55  	fi, err := os.Stat(name)
    56  	if err == nil && fi.Size() > 0 {
    57  		return nil, fmt.Errorf("can't lock file %q: %s", name, "has non-zero size")
    58  	}
    59  
    60  	handle, err := winCreateEphemeral(name)
    61  	if err != nil {
    62  		return nil, fmt.Errorf("creation of lock %s failed: %v", name, err)
    63  	}
    64  
    65  	return &winUnlocker{h: handle, abs: name}, nil
    66  }
    67  
    68  func winCreateEphemeral(name string) (windows.Handle, error) {
    69  	const (
    70  		FILE_ATTRIBUTE_TEMPORARY  = 0x100
    71  		FILE_FLAG_DELETE_ON_CLOSE = 0x04000000
    72  	)
    73  	handle, err := windows.CreateFile(windows.StringToUTF16Ptr(name), 0, 0, nil, windows.OPEN_ALWAYS, FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE, 0)
    74  	if err != nil {
    75  		return 0, err
    76  	}
    77  	return handle, nil
    78  }