blob: 542550bc8a9637546c3b7d5a136ed881e0c255ba [file] [log] [blame]
khenaidoo59ce9dd2019-11-11 13:05:32 -05001// Copyright 2016 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// +build !windows,!plan9,!solaris
16
17package fileutil
18
19import (
20 "os"
21 "syscall"
22)
23
24func flockTryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
25 f, err := os.OpenFile(path, flag, perm)
26 if err != nil {
27 return nil, err
28 }
29 if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
30 f.Close()
31 if err == syscall.EWOULDBLOCK {
32 err = ErrLocked
33 }
34 return nil, err
35 }
36 return &LockedFile{f}, nil
37}
38
39func flockLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
40 f, err := os.OpenFile(path, flag, perm)
41 if err != nil {
42 return nil, err
43 }
44 if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
45 f.Close()
46 return nil, err
47 }
48 return &LockedFile{f}, err
49}