Home > database >  How does this file descriptor and flock work?
How does this file descriptor and flock work?

Time:11-25

I want to implement a shell script to run in the background at all times. The script will be added it in startup apps for running. While trying to make sure that only one instance runs at a time, I came across this code:

#!/bin/bash
another_instance()
{
echo “There is another instance running, exiting”
exit 1
}
( flock -n 100 || another_instance DEST=/home/backup/`date  %s` mkdir -p “$DEST” rsync -avz root@myhost:/home/web “$DEST/.” ) 100>/var/lock/dobackup.lock

here, with the explanation:

In this example, we use the file descriptor 100 in the redirection to the lock file. Also, we call another_instance if flock fails, informing there is another instance and then exiting.

It works, but I do not understand the file descriptor 100 part. I tried looking online, but my confusion prevails. Could someone please explain the flock -n 100 and 100>/var/lock/dobackup.lock?

As far as I understand, flock -n creates/checks for a lock at the given /var/lock.. location, but what's the significance of 100?

Thank You.

CodePudding user response:

Is there is particular reason why wouldn't you choose writing a systemd service instead?

You didn't mentioned the operating system you are using - that can be the reason. Otherwise I would go for systemd.

You can easily track PID of process, ensure process is always started with system, etc. Some good for begin with article

CodePudding user response:

flock -n creates/checks for a lock at the given /var/lock.. location

No, flock works on file descriptors.

/var/lock is a typical location for system administrators to put locks for global utilities. Like for example for package managers (pacman, apt-get etc.). You can use (ok, almost) any file anywhere with flock.

Let's say generally, flock is a property associated with a file referenced by a file descriptor. The number 100 is not significant, it has to be any open for writing file descriptor.

100>/var/lock/dobackup.lock redirects file descriptor 100 to file /var/lock/dobackup.lock. flock -n 100 applies flock on the file descriptor 100.

See Wikipedia for file descriptor, see man 2 flock and man 2 fcntl.

  • Related