Gentoo Archives: gentoo-dev

From: Zac Medico <zmedico@g.o>
To: gentoo-dev@l.g.o
Cc: Mike Frysinger <vapier@g.o>
Subject: Re: [gentoo-dev] multiprocessing.eclass: doing parallel work in bash
Date: Mon, 04 Jun 2012 01:42:35
Message-Id: 4FCC124E.8070706@gentoo.org
In Reply to: Re: [gentoo-dev] multiprocessing.eclass: doing parallel work in bash by Mike Frysinger
1 On 06/02/2012 10:08 PM, Mike Frysinger wrote:
2 > # @FUNCTION: redirect_alloc_fd
3 > # @USAGE: <var> <file> [redirection]
4 > # @DESCRIPTION:
5 > # Find a free fd and redirect the specified file via it. Store the new
6 > # fd in the specified variable. Useful for the cases where we don't care
7 > # about the exact fd #.
8 > redirect_alloc_fd() {
9 > local var=$1 file=$2 redir=${3:-"<>"}
10 >
11 > if [[ $(( (BASH_VERSINFO[0] << 8) + BASH_VERSINFO[1] )) -ge $(( (4 << 8) + 1 )) ]] ; then
12 > # Newer bash provides this functionality.
13 > eval "exec {${var}}${redir}'${file}'"
14 > else
15 > # Need to provide the functionality ourselves.
16 > local fd=10
17 > while :; do
18 > # Make sure the fd isn't open. It could be a char device,
19 > # or a symlink (possibly broken) to something else.
20 > if [[ ! -e /dev/fd/${fd} ]] && [[ ! -L /dev/fd/${fd} ]] ; then
21 > eval "exec ${fd}${redir}'${file}'" && break
22 > fi
23 > [[ ${fd} -gt 1024 ]] && return 1 # sanity
24 > : $(( ++fd ))
25 > done
26 > : $(( ${var} = fd ))
27 > fi
28 > }
29 >
30 > fi
31
32 Where it returns 1 if [[ ${fd} -gt 1024 ]], maybe it would be best to
33 die there. It shouldn't fail there in practice, but if it does, it would
34 be really helpful to exactly where it failed.
35 --
36 Thanks,
37 Zac