如何在Shell脚本中实现单例 [英] How to implement singleton in shell script

查看:156
本文介绍了如何在Shell脚本中实现单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在kornshell中,`basename $ 0`给了我当前脚本的名称.

In kornshell, `basename $0` gives me the name of the current script.

我将如何利用$$或$ PPID来实现仅由任何用户在此服务器上执行一个名为`basename $ 0`的脚本的单例模式?

How would I exploit $$ or $PPID to implement the singleton pattern of only having one script named `basename $0` executed on this server by any user?

ps -ef|grep `basename $0`

这将向我显示所有正在运行的进程,这些进程具有当前正在运行的脚本的名称.

This will show me all processes which are running that have the name of the currently running script.

我需要一个脚本,当不是$$的线程正在运行名为"basename $ 0"的脚本时,该脚本可以中止.

I need a script which can abort when a thread which is not $$ is running the script named `basename $0`.

推荐答案

要提供无种族歧视的互斥体,flock是您的朋友.如果您不在Linux上-在由util-linux提供的中, 便携式版本可用.

To provide a race-free mutex, flock is your friend. If you aren't on Linux -- where it's provided by util-linux -- a portable version is available.

如果您确实希望将其应用于整个系统-跨用户帐户-您将需要一个目录来存放所有用户可以创建文件的锁,并且需要确保所有用户都可以写入您的锁定文件.

If you truly want it to apply to the entire system -- crossing user accounts -- you'll need a directory for your locks to live where all users can create files, and you'll need to ensure that all users can write to your lockfiles.

假设您具有flock实用程序,每个想要参与此协议的程序的行为都可以如下:

Assuming you have the flock utility, each program which wants to participate in this protocol can behave as follows:

#!/bin/ksh

umask 000                  # allow all users to access the file we're about to create
exec 9>"/tmp/${0##*/}.lck" # open lockfile on FD 9, based on basename of argv[0]
umask 022                  # move back to more restrictive file permissions
flock -x -n 9 || exit      # grab that lock, or exit the script early

# continue

一个主要注意事项:请勿在脚本退出时尝试删除锁定文件.如果您处于其他人正在积极尝试获取锁的情况下,那么他们在该现有文件上已经有文件描述符了;如果您在文件具有句柄的情况下删除该文件,则只需确保该程序可以认为该文件持有该锁,而其他人以相同的名称创建一个新文件并对其进行锁定.

One key note: Do not try to delete lockfiles when your script exits. If you're in a condition where someone else is actively trying to grab a lock, they'll already have a file descriptor on that existing file; if you delete the file while they have a handle on it, you just ensured a race wherein that program can think it holds the lock while someone else creates a new file under the same name and locks it.

这篇关于如何在Shell脚本中实现单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆