Justin
Justin

Reputation: 818

Reading from Perl pipe constantly outputting text

I recently tried to make a game server controller in Perl, I would like to start, stop and view the text that has been outputted by the game server, this is what I have so far:

     #!/usr/bin/perl -w
 use IO::Socket;
 use Net::hostent;              # for OO version of gethostbyaddr

 $PORT = 9050;                  # pick something not in use

 $server = IO::Socket::INET->new( Proto     => 'tcp',
                                  LocalPort => $PORT,
                                  Listen    => SOMAXCONN,
                                  Reuse     => 1);

 die "can't setup server" unless $server;
 print "[Server $0 accepting clients]\n";

 while ($client = $server->accept()) {
   $client->autoflush(1);
   print $client "Welcome to $0; type help for command list.\n";
   $hostinfo = gethostbyaddr($client->peeraddr);
   printf "[Connect from %s]\n", $hostinfo->name || $client->peerhost;
   print $client "Command? ";

   while ( <$client>) {
     next unless /\S/;       # blank line
     if    (/quit|exit/i) {
        last;                                     }
     elsif (/some|thing/i) {
        printf $client "%s\n", scalar localtime;  }
     elsif (/start/i ) {
        open RSPS, '|java -jar JARFILE.jar' or die "ERROR STARTING: $!\n";
        print  $client "I think it started...\n Say status for output\n";                }
     elsif (/stop/i ) {
        print RSPS "stop";
        close(RSPS);
        print  $client "Should be closed.\n"; }
     elsif (/status/i ) {
        $output = <RSPS>;
        print $client $output;      }
     else {
       print $client "Hmmmm\n";
     }
   } continue {
      print $client "Command? ";
   }
   close $client;
 }

I am having trouble reading from the pipe, any ideas?

Thanks!

Upvotes: 2

Views: 435

Answers (1)

mob
mob

Reputation: 118635

You are trying to do both reading and writing on the RSPS filehandle, though you have only opened it for writing (open RSPS, '|java -jar JARFILE.jar' means start the java process and use the RSPS filehandle to write to the standard input of the java process).

To read the output of the process, you will either need to write the process output to a file and open a separate filehandle to that file

open RSPS, '| java -jar JARFILE.jar > jarfile.out';
open PROC_OUTPUT, '<', 'jarfile.out';

or check out a module like IPC::Open3, which was made for applications like this.

use IPC::Open3;
# write to RSPS and read from PROC_OUTPUT and PROC_ERROR
open3(\*RSPS, \*PROC_OUTPUT, \*PROC_ERROR,
      'java -jar JARFILE.jar');

Upvotes: 3

Related Questions