我正在从命名管道中读取数据以与其他进程进行通信。在某些情况下,我需要丢弃命名管道中的缓冲输入,然后继续读取新输入。
我想出了以下解决方案:
! Discard the buffer of a named pipe
impure subroutine skip_ahead(unit)
integer, intent(in) :: unit !< The unit connected to the named pipe
character(len = *), parameter :: EOF = "ABC" !< String that is unlikly to occure in the named pipe
character(len = len(EOF)) :: check
write(unit = unit, fmt ='(A)') EOF
do
read(unit = unit, fmt = '(A)') check
if (trim(adjustl(check)) == EOF) return
end do
end subroutine skip_ahead
但是,我感觉可能有更好/更安全的解决方案。这是真的吗?
我想说代码的安全性可能取决于系统。在 posix 兼容系统上,对名称管道的写入似乎是原子的,假设每次写入的大小小于 PIPE_BUF:PIPE_BUF 的值可能会有所不同,但实际上似乎至少有几千字节。所以写入
ABC
是原子的,但我不知道其他进程的写入大小(如果小于 PIPE_BUF 应该没问题)。
https://www.baeldung.com/linux/pipe-buffer-capacity
另一种解决方案是使用另一个命名管道来写入 EOF 字符串,另一个进程将监视此命名管道:当读取 EOF 字符串时,它会将其写回初始命名管道。