linux-kernel - 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
事实证明,第二个命令完全覆盖了文件。脚本或实现有什么问题吗?
解决方案
是的,每个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
当然,我们这里仍然没有使用两个进程,只是在一个进程中使用两个描述符
推荐阅读
- python - Jupyter Lab 关于熊猫和情节初始导入的问题
- python-3.x - Python:识别 zip 文件的无效在线链接
- ios - 我应该将下载的声音文件(mp3 或 aac)放在 iPhone 的什么位置?
- html - 当网站页面视口包含所有页面内容时启用触摸滚动
- laravel - 在父组件中设置验证规则时,在 livewire 的子组件中显示错误消息
- python - 如何将索引分配给多值字典并将这些索引存储在多维列表中
- flutter - 如何在 Flutter 中获得手动相机对焦
- tabulator - 制表符 - 配置变量
- node.js - node.js sqlite3 在所有 db.each 异步回调完成后运行一些东西
- postgresql - postgres 提交后不保存所有数据