【问题标题】:Java sync external files read writeJava同步外部文件读写
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!现在我明白了:D
【解决方案2】:

这是我得到的:一开始,Reader 在 pipe.readLine() 中被阻塞等待。当 Writer 写一行并释放 locker 时,它会读取它。但随后 Writer 完成,Reader 不再在 readLine() 中等待,一直读取 null。

【讨论】:

  • 当作者写完后,就没有什么可等的了。没有更多数据流过连接,那么等待的意义何在?
  • 这是一个模拟,在程序中,作者会打开管道写入,而读者应该一直在等待读取这些数据。
  • 阅读器无连接时如何等待读取数据?当然,您的意思是,虽然有一个作家,但它应该等待从中读取数据。但是当编写器终止时,它应该关闭死连接并等待新的连接,而不是继续等待死连接。
猜你喜欢
  • 1970-01-01
  • 2014-08-01
  • 2011-09-12
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
相关资源
最近更新 更多