how to use flock to orchestrate running of different programs, so that they can run at different time?

StackOverflow https://stackoverflow.com/questions/16265905

  •  13-04-2022
  •  | 
  •  

Question

in a remote host, I want to run 3 programs A , B and C but I want them to run at different time so if A is running, B and C can't run so when I want to run A, if I detect that the file is locked I wait until it is unlocked

my idea is to create a lock file among these programs like mutex lock between processes like:

if file is unlocked; then lock file ./programA unlock file fi

someone told me flock can be used for this purpose I searched on google the code is like: ( flock -s 200 ./program ) 200>/var/lock/mylockfile

but I don't know how to make it as a shell script I make shell script trylock.sh like

    #!/bin/bash
    set -e

    (
    flock -x -w 10 200
    sleep 20
    ) 200 > lockfile

when I run it, I got

trylock.sh: line 7: syntax error near unexpected token `200'

Besides, how to set the lock timeout to be intinite

can anyone give some example scripts? thanks

Was it helpful?

Solution

You have extra space between 200 and >, use 200> in the redirect.

That 200 is file number, and 200> redirects that, while 200 > is nonsense, hence the syntax error.

For reference: man page of flock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top