shell script で連想配列が使えるとは今日知った…
マルチプロセスの起動と待ちも簡単。
multiprocess.sh
#!/bin/sh # $1 # 子プロセスで呼び出される関数の名前。$1に下記の配列の要素が個々に渡る。 # # $2 # 配列のgrobal変数の名前。引数として解釈する。 # 配列の個々の要素を子プロセス1つの引数とする。 # e.g.) # array[0]=0 # array[1]=1 # askChildren child array 8 # # $3 # 子プロセス最大数 # 常に最大まで使う実装にはなっていない。 # function askChildren(){ local funcname=$1 eval FUNC=\"$funcname\" local paramsname=$2 eval PARAMS=\"\${$paramsname[@]}\" local max=$3 local children local PARAM local i=0 for PARAM in ${PARAMS[@]}; do $FUNC $PARAM & echo child $! spawned children[$!]=$! i=$((i+1)) if test $i -ge $max; then wait ${children[@]} i=0 local ID for ID in ${children[@]}; do unset children[$ID] done fi #echo $i done wait ${children[@]} }
usercode.sh
#!/bin/sh source multiprocess.sh echo main pid $$ array[0]=a array[1]=b array[2]=c array[3]=d array[4]=e function child(){ echo I am child `sh -c 'echo $PPID'` } askChildren child array 3 function child2(){ echo I am child2 `sh -c 'echo $PPID'` } askChildren child2 array 3
子プロセスで起動した関数内の$$の内容
shell script 中で & を付けて子プロセスで起動した関数内では、$$
は親プロセスの内容のままになっている。
記事もあった。
https://rcmdnk.com/blog/2014/01/20/computer-bash/
それで上記 usercode.sh の child では、子プロセスから更にサブシェルを起動して、そこから親の
PPID を echo、と言うことをしている。