2010-02-11 45 views
4

我使用JNI通過調用mkfifo()命令來創建命名管道。我正在使用mode = 0666.無法從Java中的命名管道讀取

然後我嘗試使用Java寫入管道,但在寫入管道時卡住了。我被困在下面一行,無法越過它。我也沒有得到任何錯誤。

PrintWriter out = new PrintWriter((new BufferedWriter(new FileWriter(pipePath)))); 

請幫忙。

問候,

-H

PipePeer.java

import java.io.*;* 

public class PipePeer { 

    private native int createPipe(String pipeName, int mode);* // --------> native method to call mkfifo(pipeName, mode); 
    static { 
     System.load("/home/user/workspace/Pipes/libpipe.so"); 
    } 

    public static void main(String[] args) { 

     PipePeer p = new PipePeer(); 
     PipeImplement pi = new PipeImplement(); 
     String pipePath = "/home/user/workspace/Pipes/pipeFolderpipe1"; 
     int mode = 0777; 
     int createResult = p.createPipe(pipePath, mode); 
     if (createResult == 0) 
      System.out.println("Named pipe created successfully"); 
     else 
      System.out.println("Error: couldnot create Named pipe"); 


     String pipeLocation = "/home/user/workspace/Pipes/pipeFolder/pipe1"; 
     pi.writePipe("From Java", pipeLocation); 
     System.out.println(pi.readPipe(pipeLocation)); 
    } 
} 

PipeImplement.java

import java.io.*; 

public class PipeImplement { 

    public BufferedReader in; 
    public void writePipe(String strWrite, String pipePath){ 
     PrintWriter out = null; 
     try { 
     //-------------> cannot go past this line <-------------------- 
      out = new PrintWriter((new BufferedWriter(new FileWriter(pipePath)))); 
     } catch(IOException e) { 
      System.out.println("error while writing"); 
      e.printStackTrace(); 
     } 
     out.println(strWrite); 
     System.out.println("writen"); 
     out.close(); 
     System.out.println("close"); 
    } 

    public String readPipe(String pipePath) { 
     try { 
      in = new BufferedReader(new FileReader(pipePath)); 
     }catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     String lineRead = ""; 
     try { 
      lineRead = in.readLine(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return lineRead; 
    } 
} 

回答

8

那怎麼在* nix工作命名管道。你打開管道時卡住了。 打開fifo進行寫作將會阻止,直到有人打開閱讀。

如果您嘗試從同一個線程同步讀取/寫入管道,則必須進行死鎖,您必須切換到NIO,或者創建一個從fifo讀取的線程和一個寫入該線程的線程。