【发布时间】:2015-09-15 18:03:42
【问题描述】:
我想为 2 个 JVM 进程(不同进程)之间的读/写数据创建一个管道。我在 Unix 中使用 FIFO 管道来共享数据。
我做了一个阅读器:
/** Read a named pipe file */
public class PipeReader {
private String path;
public PipeReader (String path) {
this.path = path;
}
public String readpipe () throws IOException {
String res = null;
RandomAccessFile pipe = null;
try {
// Connect to the named pipe
pipe = new RandomAccessFile (path, "r");
// Read response from pipe
while (true) {
res = pipe.readLine();
System.out.println("Read message:" + res);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pipe.close();
}
return res;
}
还有一个使用 FileLock 的 Writer:
public class PipeWriter {
private String path;
public PipeWriter (String path) {
this.path = path;
}
public String writepipe (String mm) throws IOException {
String res = null;
RandomAccessFile pipe = null;
try {
// Connect to the named pipe
pipe = new RandomAccessFile (path, "rw");
FileChannel channel = pipe.getChannel();
int i = 0;
while (i<5) {
// Write request to the pipe
FileLock lock = channel.lock();
pipe.write(mm.getBytes());
lock.release();
System.out.println("PipeWriten" + mm);
Thread.sleep(3000);
i++;
}
// do something with res
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the pipe
pipe.close();
}
return res;
}
第一次 pipe.readLine() 阻塞该线程并等待 PipeWriter 在管道中写入一行并释放锁,当写入器完成阅读器读取它时。这是 PipeWriter 完成之前的行为(在 5 次写作之后)。之后, pipe.readLine() 不会阻塞线程并继续循环读取,因此我多次收到“Read message: null”。我该如何解决?我想我在阅读器中遗漏了一些东西。有什么方法可以同步2个进程共享的文件,而不是使用FileLock? (类似于信号量,但用于进程,而不是线程)。
提前致谢。
【问题讨论】:
-
问题出在作者身上。如果作者应该是可等待的,它需要保持管道打开。
-
谢谢,你是对的,我从作者那里删除了 pipe.close(),但我遇到了同样的问题。
-
在打开管道以在另一个进程中写入时,您得到了空读取?你确定吗?
-
我在一个带有图片的帖子中回答。谢谢:)。
标签: java multithreading