(bash) way to implement an idle processing loop

Bash is what it is, often a quick solution to get something done, once things start to become too advance probably should be writing in a higher level language.

With that said, here’s using tcp via bash to implement an idle processing loop:

#!/bin/bash

# Start tail command in a separate process and track PID so we can take action later
# (send output to this shell's stdout)
tail /var/logs/* > /proc/$$/fd/1 &
PID_TAIL=$!

# Idle processing loop
while (true); do

  # Perform work while 
  if <test condition>; then
  
    # Stop the tail process
    disown $PID_TAIL;
    kill $PID_TAIL;

    # Exit idle processing loop
    break;
  fi

  # avoiding maxing cpu
  sleep 1

done

The trick here is ‘$$’ is the current shell’s PID, the /proc/$$/fd/1 is a tcp device which represents the shell’s stdout. By sending the tail command to this device as a background process with ‘&’ we still see the tail output on our console. Yet, the bash script is actually in a loop able to do whatever it wants while the tail is running. When the script sees some condition it cares about it can stop the tail process and exit, or just keep working until someone presses Ctrl-c.

For more information see: https://www.xmodulo.com/tcp-udp-socket-bash-shell.html

Posted in Development.

Leave a Reply