open-file-description table不像Tanenbaum在Ubuntu中描述的那样?



在《Modern Operating System》一书中,作者解释说,如果shell脚本有两个命令p1和p2,每个命令轮流写入文件x, p1完成的位置将被p2记住,因为它们使用相同的open-file-description表。我用一个简单的脚本进行了测试。

#!/bin/bash
echo 11 > a.txt
echo 12 > a.txt

结果是第二个命令完全覆盖了文件。脚本或实现有什么问题吗?

是的,每个echo命令打开文件(并删除现有内容),向文件写入,然后关闭它。根本没有分享。

要共享打开的文件描述,请尝试:

#!/bin/bash
exec 123>a.txt # open file descriptor 123 to a.txt (note that you have to choose one, bash won't choose a number)
exec 124>&123 # open file descriptor 124 as a copy of 123 (same file description)
# now we have two file descriptors pointing to the same file description
echo 11 >&123 # write to descriptor 123
echo 12 >&124 # write to descriptor 124
exec 123>&- # close file descriptor 123
exec 124>&- # close file descriptor 124

当然,我们这里仍然没有使用两个进程,只是在一个进程中使用两个描述符

相关内容

最新更新