给定唯一名称(例如文件路径)创建本地锁

问题描述 投票:0回答:1

我有一个shell脚本,如下所示:

#!/usr/bin/env bash

set -e;
try-once-to-get-lock $(pwd) # try to get lock 
start-process  # only if lock acquired, start the desired process

我正在寻找一种实现try-once-to-get-lock进程的方法 - 我想传递一些独特的值 - 使用的最简单的唯一值就是脚本本身的文件路径,或者pwd。

有谁知道我是否可以在* nix系统上使用一些内置工具来执行此操作?如果没有,我该如何实现呢?如果可能的话,我想避免使用文件系统锁,也许还要使用端口。

node.js bash shell locking mutex
1个回答
1
投票

这个问题已在SO上多次回答。见v.gr. Is there any mutex/semaphore mechanism in shell scripts?

#!/bin/bash

lockdir=/tmp/myscript.lock
if mkdir "$lockdir"
then    # directory did not exist, but was created successfully
    echo >&2 "successfully acquired lock: $lockdir"
    # continue script
else    # failed to create the directory, presumably because it already exists
  echo >&2 "cannot acquire lock, giving up on $lockdir"
  exit 0
fi
© www.soinside.com 2019 - 2024. All rights reserved.