Skip to main content

Creating a Linux Service with PERL to read from Named Pipes

By October 2, 2013September 12th, 2022No Comments

We have looked recently at creating named pipes within Linux using mkfifo. A named pipe allows for processes to communicate with each other using the pipe. the pipe file is always zero bytes and allows only for communication between STDOUT on one process to STDIN on another process; much in the same way as unnamed pipes using the | operator in BASH. More recently we have looked at using PERL to validate POST CODES. It seemed to me then a good idea to demonstrate further the really benefits of named pipes by using them with services. So we modify the PERL script to read from the named pipe and loop waiting for input, This way the “service” can process the post codes as they are entered into the pipe. the script follows , then a step by step readinf the script followed by the video demo.

my $fifo = "pcode.pipe";
my $fifoh;
open($fifoh, "+<", $fifo) or die "The FIFO file cant be found";
while (<$fifoh>) {
 chomp ($_);
 $pattern = '^[A-Z]{1,2}[0-9]{1,2}[A-Z]?s[0-9][A-Z][A-Z]$';
 if ($_ =~ /$pattern/) {
 print "We have a match n";
 } else {
 print "No match n";
close $fifoh;

Step by Step

  1. the shebang starts the script so we know what script interpreter to use
  2. chdir(); We change to the users home directory
  3. my $fifo =”pcode.pipe”; We declare the local variable pointing to the file pcode.pipe. This should exist in the users home directory.
  4. my $fifoh; This local variable we can use as the file handle to access the file pipe. We have to have a name for the connection to the file.
  5. open($fifoh, “+<“, $fifo) ….here we populate the file handle $fifoh, by opening the file $fifo in read write mode +<. We need the read write mode so we can keep the pipe open after we process each result. The end of the line exists, die, if we are unable to open the file
  6. while (<$fifoh>) { This allows us to loop while we have the connection or file handler open to the pipe. This will loop continuously waiting for input in each loop. We can kill with control + c for this demo. In real life we would write the PID to a file and send a signal to the process ID of the script when we needed to close the service.
  7. chomp($_); $_ represents the current input and chomp removes and extra character such as line feeds from the end of the input string.
  8. The rest of the loop is from the script that we had before to check for valid UK postcodes

The video follows 🙂