Filtering the keyboard input

inputkeyboard

I have a program that takes input from the keyboard and presents a nice visualization. The purpose of the program is so that my infant can mash on the keyboard and get the computer to do something.

However, I would like to write a keyboard input sanitizer that is disjoint from the main program. Conceptually, I would want the program have the functionality:

  sanitize_keyboard_input | my_program

Where my_program thinks it is getting input from the keyboard but it is really getting input from sanitize_keyboard_input. Is there a way to do this? I am running Ubuntu linux if that helps.

Best Answer

I wrote this a long time ago. It's a script that sits between the user's input and an interactive program, and allows the input to be intercepted. I used it to escape to the shell to check filenames when running old Fortran programs that asked lots of questions. You could easily modify it to intercept particular inputs and sanitize them.

#!/usr/bin/perl

# shwrap.pl - Wrap any process for convenient escape to the shell.

use strict;
use warnings;

# Provide the executable to wrap as an argument
my $executable = shift;

my @escape_chars = ('#');             # Escape to shell with these chars
my $exit = 'bye';                     # Exit string for quick termination

open my $exe_fh, "|$executable @ARGV" or die "Cannot pipe to program $executable: $!";

# Set magic buffer autoflush on...
select((select($exe_fh), $| = 1)[0]);

# Accept input until the child process terminates or is terminated...
while ( 1 ) {
   chomp(my $input = <STDIN>);

   # End if we receive the special exit string...
   if ( $input =~ m/$exit/ ) {
      close $exe_fh;
      print "$0: Terminated child process...\n";
      exit;
   }

   foreach my $char ( @escape_chars ) {
      # Escape to the shell if the input starts with an escape character...
      if ( my ($command) = $input =~ m/^$char(.*)/ ) {
         system $command;
      }
      # Otherwise pass the input on to the executable...
      else {
         print $exe_fh "$input\n";
      }
   }
}

A simple example test program you can try it out on:

#!/usr/bin/perl

while (<>) {
   print "Got: $_";
}
Related Question