2011-03-07 61 views
2

我最近試圖用Perl製作一個遊戲服務器控制器,我想開始,停止並查看遊戲服務器輸出的文本,這就是我目前爲止所做的:從Perl管道中讀取不斷輸出的文字

 #!/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; 
} 

我無法從管道讀取任何想法?

謝謝!

回答

3

你正在試圖做的讀取和寫入的RSPS文件句柄,雖然你只打開了它寫(open RSPS, '|java -jar JARFILE.jar'方式啓動java程序,並使用RSPS文件句柄寫入java程序的標準輸入)。

要閱讀過程的輸出,你要麼需要編寫過程輸出到一個文件,然後打開一個單獨的文件句柄到該文件

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

或檢查出像IPC::Open3一個模塊,這是由對於這樣的應用程序。

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

謝謝,我會看看IPC :: Open3。 :) – Justin 2011-03-07 15:46:40