Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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: $_";
}
share|improve this answer
    
Thank you. This is very useful. I think that I will have to make some modifications to not use chomp, which does line-by-line, right? My program responds to individual key events, not separated by newline. But, I like the general idea and I can make this work. Thank you! –  stevejb Nov 4 '12 at 23:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.