-
Notifications
You must be signed in to change notification settings - Fork 4
/
waitlock.rb
executable file
·71 lines (64 loc) · 2.66 KB
/
waitlock.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env ruby
########################################################################
# waitlock.rb: File Locking Script
#
# Description:
# This Ruby script implements a simple file locking mechanism. It is designed
# to periodically check for the existence of a specified lock file and wait
# until the lock file is removed. This script is useful for coordinating tasks
# that should not run simultaneously, such as when multiple processes or tasks
# need to access a shared resource or file but should not do so at the same time.
# By checking for a lock file, the script ensures that it only proceeds once
# the resource is no longer being used by another process.
#
# The script takes two arguments: the name of the lock file and the check
# interval in seconds. While the lock file exists, the script will repeatedly
# check for its presence at the specified interval. Once the lock file is
# removed, the script stops waiting and terminates.
#
# Example Usage:
# To use the script, pass the lock file name and the check interval as arguments.
# For instance, to set the script to check for 'hoge.txt' every 1 second:
#
# ./waitlock.rb hoge.txt 1
#
# This command will cause the script to check for a lock file named 'hoge.txt'
# every 1 second. The script will continue to run (and not perform further
# actions) as long as 'hoge.txt' exists. Once 'hoge.txt' is removed, the script
# will complete its execution.
#
# Author: id774 (More info: http://id774.net)
# Source Code: https://github.com/id774/scripts
# License: LGPLv3 (Details: https://www.gnu.org/licenses/lgpl-3.0.html)
# Contact: [email protected]
#
# Version History:
# v1.2 2023-11-29
# Refactored the script for improved readability and maintainability.
# Removed unnecessary class structure and streamlined command-line argument processing.
# Added clear usage instructions and feedback messages.
# v1.1 2014-08-14
# Minor formatting and style revisions.
# v1.0 2010-12-01
# Initial release. Basic functionality for file locking with check intervals.
#
########################################################################
# Check for the existence of a lock file at regular intervals
def wait_for_lock_release(lockfile, interval)
while File.exist?(lockfile)
puts "Waiting for lock file #{lockfile} to be released..."
sleep(interval)
end
end
# Main execution logic
def main
if ARGV.length != 2
puts "Usage: #{$PROGRAM_NAME} lockfile_name interval_in_seconds"
exit(1)
end
lockfile = ARGV[0]
interval = ARGV[1].to_i
wait_for_lock_release(lockfile, interval)
puts "Lock file released, proceeding..."
end
main if __FILE__ == $PROGRAM_NAME