同步Shell脚本执行 [英] Synchronize shell script execution

查看:693
本文介绍了同步Shell脚本执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

shell脚本的修改版将音频文件从FLAC转换为MP3格式.该计算机具有四核CPU.该脚本使用以下命令运行:

A modified version of a shell script converts an audio file from FLAC to MP3 format. The computer has a quad-core CPU. The script is run using:

./flac2mp3.sh $(find flac -type f)

这会将flac目录中的FLAC文件(文件名中没有空格)转换为mp3目录中的MP3文件(与flac处于同一级别).如果目标MP3文件已经存在,则脚本将跳过该文件.

This converts the FLAC files in the flac directory (no spaces in file names) to MP3 files in the mp3 directory (at the same level as flac). If the destination MP3 file already exists, the script skips the file.

问题在于,有时脚本的两个实例几乎同时检查同一MP3文件的存在,从而导致MP3文件损坏.

The problem is that sometimes two instances of the script check for the existence of the same MP3 file at nearly the same time, resulting in mangled MP3 files.

您如何运行脚本多次(即每个内核一次),而不必在每个命令行上指定不同的文件集,又无需覆盖工作?

How would you run the script multiple times (i.e., once per core), without having to specify a different file set on each command-line, and without overwriting work?

更新-最低比赛条件

该脚本使用以下锁定机制:

The script uses the following locking mechanism:

  # Convert FLAC to MP3 using tags from flac file.
  #
  if [ ! -e $FLAC.lock ]; then
    touch $FLAC.lock
    flac -dc "$FLAC" | lame${lame_opts} \
      --tt "$TITLE" \
      --tn "$TRACKNUMBER" \
      --tg "$GENRE" \
      --ty "$DATE" \
      --ta "$ARTIST" \
      --tl "$ALBUM" \
      --add-id3v2 \
      - "$MP3"
    rm $FLAC.lock
  fi;

但是,这仍然留下了竞争条件.

However, this still leaves a race condition.

推荐答案

"lockfile"命令提供了您在没有竞争条件的情况下要为shell脚本执行的操作.该命令是由procmail人士专门针对这种目的编写的,并且在大多数BSD/Linux系统上都可以使用(因为procmail在大多数环境中都可用).

The "lockfile" command provides what you're trying to do for shell scripts without the race condition. The command was written by the procmail folks specifically for this sort of purpose and is available on most BSD/Linux systems (as procmail is available for most environments).

您的测试变成这样:

lockfile -r 3 $FLAC.lock
if test $? -eq 0 ; then
  flac -dc "$FLAC" | lame${lame_opts} \
    --tt "$TITLE" \
    --tn "$TRACKNUMBER" \
    --tg "$GENRE" \
    --ty "$DATE" \
    --ta "$ARTIST" \
    --tl "$ALBUM" \
    --add-id3v2 \
    - "$MP3"
fi
rm -f $FLAC.lock

或者,您可以使lockfile无限期地重试,这样就不必测试返回代码,而可以测试输出文件以确定是否运行flac.

Alternatively, you could make lockfile keep retrying indefinitely so you don't need to test the return code, and instead can test for the output file for determining whether to run flac.

这篇关于同步Shell脚本执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆