Skip to content

Instantly share code, notes, and snippets.

@colejhudson
Created December 6, 2017 01:41
Show Gist options
  • Select an option

  • Save colejhudson/1cdddc5cb7fa958314dea6443533fd48 to your computer and use it in GitHub Desktop.

Select an option

Save colejhudson/1cdddc5cb7fa958314dea6443533fd48 to your computer and use it in GitHub Desktop.
Using file descriptors to coordinate processes and paralized tasks in bash.
#!/usr/bin/env bash
function sub_proc_test() {
START=${SECONDS}
echo "[1] pid:${$}"
(
echo "[2] pid:${$}"
while read line; do [[ -z $line ]] && exit; echo "[2] ${line}" >&100; done
) 100> >(
echo "[3] pid ${$}"
while read line; do echo "[3] ${line}"; done
) < <(cat -- \
<(echo "[4]"; echo "[4] test 1"; echo "[4] test 2") \
<(echo "[5]"; echo "[5] sleep test 1"; sleep 1; echo "[5] sleep test 2") \
<(echo "[6]";{ sleep 1 && echo "[6] async test 1" & };echo "[6] async test 2")
)
echo "[1] pid:${$}"
END=${SECONDS}
ELAPSED=$(( END - START ))
echo "Time: ${ELAPSED}"
}
# Below we can see the blocking behavior of 'cat' in that processes 4, 5, and 6
# occur sequentially. Although intra-process we can see that asyncronous behavior
# is possible as seen in the output of process 6.
# We can also see that we first call process 2 which reads the input, and passes it
# into the fd 100, which is then outputted into the process 3, such that process 2
# is composed with process 3 in a 'pass by reference' style. Where 'pass by value'
# would be piping.
# time sub_proc_test
# [1] pid:18994
# [3] pid 18994
# [2] pid:18994
# [3] [2] [4]
# [3] [2] [4] test 1
# [3] [2] [4] test 2
# [3] [2] [5]
# [3] [2] [5] sleep test 1
# [3] [2] [5] sleep test 2
# [3] [2] [6]
# [3] [2] [6] async test 2
# [3] [2] [6] async test 1
# [1] pid:18994
# Time: 1
#
# real 0m1.009s
# user 0m0.000s
# sys 0m0.008s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment