我想在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的作家:
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? (像信号量,但是对于进程,而不是线程)。
提前致谢。