【问题标题】:Reading from Perl pipe constantly outputting text从 Perl 管道读取不断输出文本
【发布时间】:2011-03-07 15:10:06
【问题描述】:

我最近尝试在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;
 }

我无法从管道中读取,有什么想法吗?

谢谢!

【问题讨论】:

    标签: perl pipe named-pipes


    【解决方案1】:

    您正在尝试对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');
    

    【讨论】:

    • 谢谢,我会研究 IPC::Open3。 :)
    猜你喜欢
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多