无法从Java中的命名管道读取

use*_*290 4 java named-pipes

我通过调用mkfifo()命令使用JNI创建命名管道.我使用的是mode = 0666.

我正在尝试使用Java写入管道,但是在写入管道时我遇到了问题.我被困在以下一行并且无法通过它.我也没有收到任何错误.

PrintWriter out = new PrintWriter((new BufferedWriter(new FileWriter(pipePath))));
Run Code Online (Sandbox Code Playgroud)

请帮忙.

问候,

-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));
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

lee*_*roy 8

这就是*nix上命名管道的工作方式.你在打开管道时遇到了困难.打开一个写作的fifo将阻止,直到有人打开它进行阅读.

如果您尝试同步从同一个线程读取/写入管道,您将死锁,您必须切换到NIO,或创建一个从fifo读取的线程和一个写入它的线程.