1

I have some script using flock executable. It works well. Problem is when this script calls another script, and it creates background process. In this situation background process inherits file locked file handle, this is system behavior. I'm looking for any tool that works as wrapper and close all unneeded handles, specially for with file locks.

In my idea only main process shoud be protected against running twice. I know this is untypical sytuation. Usually all children should finish for leaving file lock, but in this situation this does not work.

At now I use some workaround, using some wrapper with main code above, but I'd preffer use some binary wrapper.

code:

#!/bin/bash
for fd in $(ls /proc/$$/fd); do
case "$fd" in
0|1|2|255)
    ;;
*)
eval "exec $fd>&-"
    ;;
    esac
done
exec $1 $2 $3 $4 $5 $6 $7 $8 $9
2

Your script seems good enough. There are just some improvements needed:

#!/bin/bash
shopt -s nullglob
for fd in "/proc/$$/fd/"*; do
    fd=${fd##*/}
    case "$fd" in
    0|1|2|255)
        ;;
    *)
        eval "exec $fd>&-"
        ;;
    esac
done
exec "$@"
  • nullglob prevents the pattern from presenting itself if no file is found.
  • Globbing or filename expansion with the help of ${v##pat} parameter substitution method is enough. Using ls is not needed.
  • You can just use "$@" to represent all arguments passed unto the script.

The script is guaranteed to run without any external dependency so it's as good as running a binary.

2

You want to run a background job that's isolated from its caller. This sounds a lot like a daemon.

Unfortunately, there's no standard utility to start a program as a dameon. Debian and derivatives provide start-stop-daemon, but that's unfortunately not portable to other distributions. You can install daemonize, which will run on most unix variants.

  • It's interesting, but i must keep stdout opened because I get result from stdout. I use debian. For me this is strange start-stop-daemon isn't ported to other linux distros. This info is usefull unfortunately not in this situation. – Znik Aug 6 '14 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.