#!/bin/perl
# File: execer
# Demonstrate a parent creating a child who exec's another program.

print "File to sort? ";
chomp($sortfile = <STDIN>);

if (-f $sortfile) {
   print "CAUTION: FILE $sortfile WILL BE MODIFIED!\n";
   print "Continue? (y/n) ";
   chomp($answer = <STDIN>);
   if ($answer ne "y") { exit(0) };   # Bail out
}
else {
   print "Can't find file $sortfile.\n";
   exit(-1);
}

system("cat $sortfile");

# Call fork to create a child process
if (($pid = fork) == 0) {   # Child branch
   exec("sort $sortfile -o$sortfile") || die "Couldn't exec sort: $!\n";
   exit(0);        # Should never get here
}
else {             # Parent branch
   # Pretend that we have some work to do here while the child sorts the 
   # file ...
   waitpid($pid,0);   # Now wait for child to finish (it may be finished 
		      # by the time we get to waitpid).
   # Now proceed on and process the sorted file.
   # ...
   print "---\n";  # A cute separator
   system("cat $sortfile");
}  # End of parent
