Socat to share a serial link between multiple processes

I found a solution. It involves 4 instances of socat, arranged in the network diagram below:

                               /-<-[A - udp receiver] <=udp= [D - udp sender]-<-\
ttyS0 <--> [B - serial adapter]                                                  [C - tcp adapter] <=tcp=> Process A
                               \->-------------------------------------------->-/
  • Socat "B" talks to the serial port, takes input on stdin and outputs to stdout.
  • Socat "A" listens for UDP packets from anywhere and outputs them over stdout, where they are piped into socat "B".
  • Socat "C" listens for a TCP connection from Process A. Data coming from socat "A" comes in stdin and is routed to Process A. Data from Process A is sent out stdout to socat "D".
  • Socat "D" takes data from stdin and sends it out over UDP to socat "A".

Process B sends UDP packets to socat "B" when it wants to inject traffic.

The bash command to create this monstrosity is as follows:

socat -d -d -d -lpA_udp_rxr -u -T5 udp-recv:1111 - 2>>log.txt |
socat -d -d -d -lpB_serial_adapter -t5 - /dev/ttyS0,raw 2>>log.txt |
socat -d -d -d -lpC_tcp_adapter -T5 - tcp4-listen:3333 2>>log.txt |
socat -d -d -d -lpD_udp_sender -u -T5 - udp:localhost:1111,sourceport=2222 2>>log.txt 

This also sets a timeout of 5 seconds and logs a lot of detail to "log.txt". Port numbers replaced for security.