我正在编写一个bash脚本,该脚本启动多个都写入同一文件的多个后台脚本。我的脚本如下所示:
for (( COUNTER=0; ...)); do
./otherscript a b &
done
wait
和./otherscript看起来像这样:
echo $1 $2 >> file.txt
这样安全吗?这些脚本可能在后台运行数百个,它们将在Debian和Ubuntu系统上运行。
在模式下的POSIX兼容文件系统(ext4,XFS等)上O_APPEND
(这可以>>
为您提供),无论您有多少个进程,写操作总会移到最底端。此外,如果这些写入适合单个存储器页面,则没有风险将它们分成多个单独添加的组件。
因此,这是不安全的:
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),则它们可能会拆分为多个syscall,但请尽量简短,并确保每个记录都包含完整的记录,并且您是安全的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句