Inside a BASH script we can have multiple processes running in background which intercommunicate using named pipes, FIFOs registered on the filesystem. An example of this could be:
#!/bin/bash
mkfifo FIFO
# BG process 1
while :; do echo x; done & >FIFO
# BG process 2
while :; do read; done & <FIFO
exit
I wonder if it's possible to do the same intercommunication between background processes of a script without using a FIFO on filesystem, maybe with some kind of file-descriptor redirection.
Have you considered the use of signals? If the only thing you need is to trigger an event (without passing arguments), using kill and trap works perfectly (be careful of the semantics though, use SIGUSR1 for instance).
You might need to rework the logic though, as in the example below:
You could use
nc
(akanetcat
) which allows connecting a script's standard streams to a network socket. Of course it also works on localhost, so you can use it for IPC between scripts. The bonus is the possibility to have scripts running on different hosts, which is not possible with FIFOs (OK, maybe on NFS it is, but that would be rather cumbersome to set up unless you already have the NFS in place).I just want to point out that ugly hacks didn't wish to be born that way.
Part which receives data:
Part which sends data:
Works even in MSysGit's Bash for Windows, to my surprise.
Here's an example that runs two subprocesses implemented as functions of the same shell-script... One subprocess generates numbers 1...5 (sleeps in between prints), the second one reads from a fixed filedescriptor (5, to which STDOUT of the first FD is redirected to), multiplies by 2 and prints again. The main process redirects STDOUT of that second process to another fixed filedescriptor (6) and later on reads from that one in the loop.
It works basically the same as you'd do in C-code with fd pairs created by the pipe(2) system call. To understand what's happening run the script under strace -f!
Bash Version is 4.2.24(1) running on Ubuntu/x86.
Output of script:
Source code:
Process tree while running:
Bash 4 has coprocesses.
You can also use anonymous named pipes, aka process substitution in Bash 2, 3 or 4.