Answers:
设置锁的非常简单的方法:
if mkdir /var/lock/mylock; then
echo "Locking succeeded" >&2
else
echo "Lock failed - exit" >&2
exit 1
fi
要运行的脚本需要创建锁。如果该锁存在,则另一个脚本正忙,因此第一个脚本无法运行。如果该文件不存在,则说明没有脚本获得该锁。因此,当前脚本获得了锁。脚本完成后,需要通过删除锁来重新获得锁。
有关bash锁的更多信息,请查看此页
无需安装一些精美的软件包:
#!/bin/bash
pgrep -xf "$*" > /dev/null || "$@"
自己编写该脚本比运行“ apt-get install”更快,不是吗?您可能要在pgrep中添加“ -u $ {id -u)”以检查仅由当前用户运行的实例。
||
操作员的另一端,而这两个脚本都有机会启动该脚本。
另请参见Tim Kay的solo
,它通过在用户唯一的回送地址上绑定端口来执行锁定:
如果他的网站出现故障:
用法:
solo -port=PORT COMMAND
where
PORT some arbitrary port number to be used for locking
COMMAND shell command to run
options
-verbose be verbose
-silent be silent
像这样使用它:
* * * * * solo -port=3801 ./job.pl blah blah
脚本:
#!/usr/bin/perl -s
#
# solo v1.7
# Prevents multiple cron instances from running simultaneously.
#
# Copyright 2007-2016 Timothy Kay
# http://timkay.com/solo/
#
# It is free software; you can redistribute it and/or modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software Foundation;
# either version 1 (http://dev.perl.org/licenses/gpl1.html), or (at your option)
# any later version (http://www.fsf.org/licenses/licenses.html#GNUGPL), or
#
# b) the "Artistic License" (http://dev.perl.org/licenses/artistic.html), or
#
# c) the MIT License (http://opensource.org/licenses/MIT)
#
use Socket;
alarm $timeout if $timeout;
$port =~ /^\d+$/ or $noport or die "Usage: $0 -port=PORT COMMAND\n";
if ($port)
{
# To work with OpenBSD: change to
# $addr = pack(CnC, 127, 0, 1);
# but make sure to use different ports across different users.
# (Thanks to www.gotati.com .)
$addr = pack(CnC, 127, $<, 1);
print "solo: bind ", join(".", unpack(C4, $addr)), ":$port\n" if $verbose;
$^F = 10; # unset close-on-exec
socket(SOLO, PF_INET, SOCK_STREAM, getprotobyname('tcp')) or die "socket: $!";
bind(SOLO, sockaddr_in($port, $addr)) or $silent? exit: die "solo($port): $!\n";
}
sleep $sleep if $sleep;
exec @ARGV;
solo(3801): Can't assign requested address
除非您0
为method的第3个参数强制输入a ,否则它将失败并显示错误pack
。对BSD有好处的对Mac也有好处。
来自bash-hackers.org的一个对我有用的简单解决方案是使用mkdir。这是一种简单的方法,可确保仅运行程序的一个实例。使用mkdir .lock创建一个目录,该目录返回
因此,这个简单的功能完成了所有文件锁定逻辑:
if mkdir .lock; then
echo "Locking succeeded"
eval startYourProgram.sh ;
else
echo "Lock file exists. Program already running? Exit. "
exit 1
fi
echo "Program finished, Removing lock."
rm -r .lock
echo "Locking succeeded" >&2; trap 'rm -rf /var/lock/mylock' EXIT