2010-04-18 105 views
1

我需要編寫一個將腳本輸入到Java程序中的Perl腳本。這與this有關,但這並沒有幫助我。我的問題是,Java應用程序沒有得到打印語句,直到我關閉句柄。我在網上找到的是$ |需要設置爲大於0的值,在這種情況下,換行符將刷新緩衝區。這仍然不起作用。如何使用Perl將輸入輸入到Java應用程序?

這是腳本:

#! /usr/bin/perl -w 

use strict; 
use File::Basename; 

$|=1; 

open(TP, "| java -jar test.jar") or die "fail"; 
sleep(2); 

print TP "this is test 1\n"; 
print TP "this is test 2\n"; 
print "tests printed, waiting 5s\n"; 
sleep(5); 

print "wait over. closing handle...\n"; 
close TP; 
print "closed.\n"; 

print "sleeping for 5s...\n"; 
sleep(5); 
print "script finished!\n"; 
exit 

這裏是一個樣本Java應用程序:

import java.util.Scanner; 

public class test{ 

    public static void main(String[] args){ 

     Scanner sc = new Scanner(System.in); 
     int crashcount = 0; 
     while(true){ 
      try{ 
       String input = sc.nextLine(); 
       System.out.println(":: INPUT: " + input); 
       if("bananas".equals(input)){ 
        break; 
       } 
      } catch(Exception e){ 
       System.out.println(":: EXCEPTION: " + e.toString()); 
       crashcount++; 
       if(crashcount == 5){ 
        System.out.println(":: Looks like stdin is broke"); 
        break; 
       } 
      } 
     } 
     System.out.println(":: IT'S OVER!"); 
     return; 
    } 

} 

的Java應用程序應該立即接受測試打印響應,但它沒有,直到在Perl腳本中關閉語句。我究竟做錯了什麼?

注意:修復程序只能在Perl腳本中。 Java應用程序無法更改。此外,File :: Basename在那裏,因爲我在真實腳本中使用它。

回答

2

$ | = 1僅適用於當前選定的文件句柄(默認爲標準輸出)。爲了使您的TP文件處理熱,你需要打開它後,要做到這一點:

select(TP); 
$| = 1; 
select(STDOUT); 
+0

你贏了 - 謝謝你! – 2010-04-18 03:08:54

3

我已經長大了,而喜歡的IO::Handle衍生模塊。它們可以輕鬆控制刷新,讀取數據,二進制模式以及句柄的許多其他方面。我們使用IO::File

use IO::File; 

my $tp = IO::File->new("| java -jar test.jar") 
    or die "fail - $!"; 

# Manual print and flush 
$tp->print('I am fond of cake'); 
$tp->flush; 

# print and flush in one method 
$tp->printflush('I like pie'); 

# Set autoflush ON 
$tp->autoflush(1); 
$tp->print('I still like pie'); 

此外,由於文件句柄詞法範圍,您不必手動關閉它。它會在超出範圍時自動關閉。

順便說一句,除非你的目標是一個perl舊的5.6,你可以使用warnings編譯指示,而不是-w。有關更多信息,請參閱perllexwarn

相關問題