3

I have a task to rsync a dir from remote server

rsync -av root@s0.foo.com:/srv/data/ /srv/data/ 

To make it run regularly and avoid Script "reEnter" issue, I create a file lock "in_progress" with rsync progress's pid, which indicate whether the program is still running.

lock(){
    echo $1 > in_progress
}

Using this function to judge whether the rsync progress is still running:

is_running(){
   pid=$(cat in_progress)
   return ps aux | awk '{print $2}' | grep $pid
}

I can get the pid to pass to function lock with this

$!

I had to put the rsync progress background to get the pid of rsync, so I get this

rsync -av root@s0.foo.com:/srv/data/ /srv/data/ & 
lock $!

but when rsync progress is done, I should rm the lock file
I tried this

rsync -av root@s0.foo.com:/srv/data/ /srv/data/ && rmLock & 
lock $!

... then it seems the pid I got is not the pid of rsync progress :-(

armnotstrong
  • 8,605
  • 16
  • 65
  • 130
  • possible duplicate of [How to prevent a script from running simultaneously?](http://stackoverflow.com/questions/169964/how-to-prevent-a-script-from-running-simultaneously) – Palec Oct 06 '14 at 23:24
  • It is good to indicate that your issue is solved by accepting an answer that was useful. – Juan Diego Godoy Robles Nov 25 '15 at 20:39

3 Answers3

3

If you want to prevent simultaneous executions , flock is a nice tool:

$ flock -n /path/to/lock/file -c "rsync -av root@s0.foo.com:/srv/data/ /srv/data/" &
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
0
( rsync -av root@s0.foo.com:/srv/data/ /srv/data/ && rmLock ) & 

Also

[ -d /proc/$pid ] && …
tijagi
  • 1,124
  • 1
  • 13
  • 31
  • `( rsync -av root@s0.foo.com:/srv/data/ /srv/data/ && rmLock ) & `seems cant get the pid of rsync, but the bash pid start the command – armnotstrong Sep 16 '14 at 08:42
-1

I just find a way to solve this, using wait

rsync -av root@s0.foo.com:/srv/data/ /srv/data/ &
pid=$!
lock $pid
wait $pid
rmLock $pid

thanks to tijagi, I found a more elegant way to judge whether a progress is running.

armnotstrong
  • 8,605
  • 16
  • 65
  • 130