【问题标题】:open-file-description table is not like what Tanenbaum described in Ubuntu?open-file-description 表不像 Tanenbaum 在 Ubuntu 中描述的那样?
【发布时间】:2021-05-22 13:38:50
【问题描述】:

在《现代操作系统》一书中,作者解释说,如果shell脚本有两个命令,p1和p2,每个命令轮流写入一个文件x,p1完成的位置将被p2记住,因为他们正在使用相同的打开文件描述表。我用一个简单的脚本对此进行了测试。

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

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

【问题讨论】:

  • 操作>(重新)写入文件,操作>>追加到文件。可能,您想使用后者:echo 12 >> a.txt
  • 第一版是 1992 年,当时 ast 是一个 Linux basher。

标签: linux-kernel operating-system ext2


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 2011-01-11
    • 2020-04-04
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多