我正在编写一个启动多个后台脚本的 bash 脚本,这些脚本都写入同一个文件。我的脚本如下所示:
for (( COUNTER=0; ...)); do
./otherscript a b &
done
wait
和 ./otherscript 看起来像这样:
echo $1 $2 >> file.txt
这样做安全吗?这些脚本中可能有 100 多个在后台运行,并且这些脚本将在 Debian 和 Ubuntu 系统上运行。
最佳答案
在 O_APPEND
模式(>>>
给你的)POSIX 兼容文件系统(ext4、XFS 等)上,无论你有多少进程, 写总是会走到底部;此外,如果这些写入适合单个内存页,则不会存在将它们拆分为多个单独附加的组件的风险。
所以,这是不安全的:
exec >>somefile # redirects all future stdout to somefile in O_APPEND mode
printf %s 'Hello' # BUGGY: Writing less than a line, so you can get split at this point
echo ' World'
...这是这样的:
exec >somefile # truncate file and make all future writes go to it, NOT in O_APPEND mode
echo "Hello World" # BUGGY: Not opened with O_APPEND, so our file pointer may not be
# ...at the end after other programs have been doing concurrent writes.
...但这是安全的:
exec >>somefile # redirects all future stdout to somefile in O_APPEND mode
echo "Hello World" # SAFE: Writing a complete line, less than 4kb, in O_APPEND mode.
需要注意的是,如果您的写入大于一个页面(通常为 4kb),它们可能会被分成多个系统调用——但要保持简短,并确保每个系统调用都包含完整记录,这样您就安全了。
关于BASH:让多个 bash 后台进程写入同一个文件是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848172/