首页 > 解决方案 > open-file-description 表不像 Tanenbaum 在 Ubuntu 中描述的那样?

问题描述

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

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

事实证明,第二个命令完全覆盖了文件。脚本或实现有什么问题吗?

标签: linux-kerneloperating-systemext2

解决方案


是的,每个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

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


推荐阅读