#!/bin/perl
# File: pageit

# Call subroutine fprint to print a file with paging
# --------------------------------------------------
  &fprint("/etc/services"); 
  exit(0);

# ================================================================
# Subroutine fprint
# ================================================================
sub fprint {
  local($pagefile) = @_;
  local($stdin) = SI;
  local($stdout) = SO;
  local($pid);

# Check to make sure the argument file exists
# -------------------------------------------
  if (! -f $pagefile) {
     print "$pagefile not there\n";
     return  -1;
  }

# Save STDIN and STDOUT for later restoration to filenos 0 and 1
# --------------------------------------------------------------
  open($stdin, ">&STDIN");
  open($stdout, ">&STDOUT");

# Create a pipe on 0 and 1 for inheritance across fork
# ----------------------------------------------------
  pipe(STDIN, STDOUT);   # STDIN/STDOUT are read/write

# Fork and exec the pager 'more'
# ------------------------------
  if (($pid = fork) == 0) {
     close(STDOUT);        # Close write end of pipe in child
     open(STDOUT, ">&$stdout"); # Re-establish stdout for child
     exec("/usr/bin/more") || die $stdout "exec failed: $!\n";
     exit;
  }

  close(STDIN);      # Close read side of pipe
  select STDOUT;     # Select pipe as default for print

# Pipe the file into the pager
# ----------------------------
  open($pagefile, "$pagefile");
  while (<$pagefile>) {
     print;
  }

# Finish up
# ---------
  close(STDOUT);     # Close write end so reader will get EOF on pipe
  waitpid($pid, 0);  # Wait for the reader (child) to terminate
   
# Restore STDIN and STDOUT to 0 and 1
# -----------------------------------
  open(STDIN, ">&STDIN");
  open(STDOUT, ">&STDOUT");
  select STDOUT;     # Select original stdout
}
