How can I lock a file using Linux (CygWin) shell scripting?
I need to detect it later in the code of another shell scripting.
Reason for doing this: I have two Linux (CygWin) shell scripts (named A and B), and would like to use file locking to make the first (A) to be able detect if the second (B) is running.
Even when there are other methods to detect if a program is running, I would like to learn the filelocking method, since it could some day have advantages.
Asked
Active
Viewed 2,087 times
3

Sopalajo de Arrierez
- 3,543
- 4
- 34
- 52
-
Possible duplicate of [Quick-and-dirty way to ensure only one instance of a shell script is running at a time](https://stackoverflow.com/questions/185451/quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at) – Xiong Chiamiov Jan 24 '18 at 21:39
-
I should point out that Linux IS NOT Cygwin or, visa versa. This is the reason people push the term "GNU/Linux" to refer to what people usually call the "Linux" OS. The better term to use is a \*NIX because almost ever bit of this applies to any UNIX, *including* Mac OX (which is a UNIX), although `flock` is from [`util-linux`](https://karelzak.blogspot.com/), which is a Linux project... Somehow I don't feel that I've made things clearer here :( – Daniel Santos Jan 03 '20 at 03:14
1 Answers
3
Use flock
for both things: locking a file during the execution of the script B and checking the lock status from the script.
When launching script B:
flock /tmp/lockfile.lck ScriptB.sh
Inside script A, to detect the lock:
flock -n /tmp/lockfile.lck echo "Script B is not running" || echo "Script B is running right now"
The '-n' option makes flock
to "not wait" for the releasing (the default action) of the lock file. Thus, that would be another way of using flock, if waiting is what you desire.

Sopalajo de Arrierez
- 3,543
- 4
- 34
- 52
-
flock looks perfect... but I can't seem to find it in cygwin or cygwin64, which this question is tagged. Am I missing something? – WernerCD Jan 14 '15 at 15:33
-
1