Ai
5 Star 6 Fork 4

zstackio/zstack-vyos

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
flock.go 1.09 KB
一键复制 编辑 原始数据 按行查看 历史
shixin.ruan 提交于 2021-05-18 14:36 +08:00 . [BugFix: ZSTACK-xxx] add vyos ut
package utils
import (
"fmt"
"os"
"syscall"
)
// Filelock defines an file lock (shared or exclusive).
type Filelock struct {
file *os.File
}
func doLockFile(path string, mode int) (*Filelock, error) {
// A shared or exclusive lock can be placed on a file regardless
// of the mode in which the file was opened.
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0640)
if err != nil {
return nil, fmt.Errorf("open %s: %s", path, err)
}
err = syscall.Flock(int(file.Fd()), mode)
if err != nil {
file.Close()
return nil, fmt.Errorf("lock %s: %s", path, err)
}
return &Filelock{file}, nil
}
// LockFileShar imposes a share lock on a file
func LockFileShar(path string) (*Filelock, error) {
return doLockFile(path, syscall.LOCK_SH)
}
// LockFileExcl locks a file exclusively.
func LockFileExcl(path string) (*Filelock, error) {
return doLockFile(path, syscall.LOCK_EX)
}
// Unlock unlocks a lock holding by current process.
func (lck *Filelock) Unlock() error {
file := lck.file
err := syscall.Flock(int(file.Fd()), syscall.LOCK_UN)
file.Close()
os.Remove(file.Name())
return err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zstackio/zstack-vyos.git
git@gitee.com:zstackio/zstack-vyos.git
zstackio
zstack-vyos
zstack-vyos
master

搜索帮助