سؤال

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.

هل كانت مفيدة؟

المحلول

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 flockto "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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top