我正在为 IPC 使用命名管道。有时进程之间发送的数据可能很大而且很频繁。在这段时间里,我看到很多数据丢失。下面的代码中是否存在任何可能导致此问题的明显问题?
谢谢
#!/usr/bin/env groovy
import java.io.FileOutputStream;
def bytes = new File('/etc/passwd').bytes
def pipe = new File('/home/mohadib/pipe')
1000.times{
def fos = new FileOutputStream(pipe)
fos.write(bytes)
fos.flush()
fos.close()
}
#!/usr/bin/env groovy
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
def pipe = new File('/home/mohadib/pipe')
def bos = new ByteArrayOutputStream()
def len = -1
byte[] buff = new byte[8192]
def i = 0
while(true)
{
def fis = new FileInputStream(pipe)
while((len = fis.read(buff)) != -1) bos.write(buff, 0, len)
fis.close()
bos.reset()
i++
println i
}
最佳答案
当最后一个进程关闭时,命名管道会丢失其内容。在您的示例中,如果写入进程在读取进程即将执行 fis.close()
时执行另一次迭代,则可能会发生这种情况。这种情况下没有报错。
一个可能的解决方法是安排读取进程永远不会关闭 fifo。为了摆脱最后一个写入者断开连接时的EOF条件,打开fifo进行写入,关闭读取端,重新打开读取端并关闭临时写入端。
关于Linux - 命名管道 - 丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4867780/