Java同步外部文件读写

埃斯特万S

我想为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()不会阻塞线程并继续循环读取,因此很多时候我都会收到“读取消息:空”消息。我该如何解决?我认为我在阅读器中缺少某些内容。是否有任何方法可以同步2个进程共享的文件,而不使用FileLock?(类似于信号灯,但用于进程,而不是线程)。

提前致谢。

大卫·施瓦兹(David Schwartz)

管道不像文件(这很好,因为您不能等待文件),它是读取器和写入器之间的连接。它更像是一部电话。当另一侧挂断电话时,您也必须挂断电话。然后,您可以等待下一个呼叫。

read为零时,这意味着连接现在已关闭,您应该关闭管道。如果要等待新的连接,请重新打开管道。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章