如果已经在运行,则Bash脚本等待,然后继续

时间:2021-02-07 16:20:29

I have a bash script that is called by a program once a process is complete. I need a way for that bash script to wait if another instance of itself is running to exit before continuing. I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.

我有一个bash脚本,该脚本在进程完成时由程序调用。我需要一种方法,让bash脚本在运行另一个实例时等待退出,然后再继续。我不能只使用锁文件和退出,因为脚本不会在任何常规调度中再次被调用。

2 个解决方案

#1


1  

I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.

我不能只使用锁文件和退出,因为脚本不会在任何常规调度中再次被调用。

Within the script, before creating the lock file, you can loop through checking if the lock file exists, if it does, continue looping (through a sleep command or something) and when it goes away, create it.

在脚本中,在创建锁文件之前,您可以通过检查锁文件是否存在,如果它确实存在,继续循环(通过一个sleep命令或其他什么),当它消失时,创建它。

Something like:

喜欢的东西:

#!/bin/bash

while [ -e /var/tmp/bash_script.lock ];
do
    sleep 5
done

touch /var/tmp/bash_script.lock

echo "do something"

rm /var/tmp/bash_script.lock

#2


1  

use ps -df command which lists all the PIDs and PPIDs running on your system. Now you can include a code that will parse ps -df output and check for running instances of bash script iy answer is yes exit 1 the present script

使用ps -df命令列出系统上运行的所有pid和ppid。现在,您可以包含一个代码,它将解析ps -df输出,并检查bash脚本iy的运行实例是yes退出当前脚本。

#1


1  

I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.

我不能只使用锁文件和退出,因为脚本不会在任何常规调度中再次被调用。

Within the script, before creating the lock file, you can loop through checking if the lock file exists, if it does, continue looping (through a sleep command or something) and when it goes away, create it.

在脚本中,在创建锁文件之前,您可以通过检查锁文件是否存在,如果它确实存在,继续循环(通过一个sleep命令或其他什么),当它消失时,创建它。

Something like:

喜欢的东西:

#!/bin/bash

while [ -e /var/tmp/bash_script.lock ];
do
    sleep 5
done

touch /var/tmp/bash_script.lock

echo "do something"

rm /var/tmp/bash_script.lock

#2


1  

use ps -df command which lists all the PIDs and PPIDs running on your system. Now you can include a code that will parse ps -df output and check for running instances of bash script iy answer is yes exit 1 the present script

使用ps -df命令列出系统上运行的所有pid和ppid。现在,您可以包含一个代码,它将解析ps -df输出,并检查bash脚本iy的运行实例是yes退出当前脚本。