我正在使用终端将多个命令的输出同时传送到同一文件中:
cmd1 | tee -a /tmp/file
cmd2 | tee -a /tmp/file
cmd3 | tee -a /tmp/file
使用安全吗?此方法是否存在任何数据丢失或读/写权限问题?
编辑:我可以混合输出,我只想确保所有内容都写入文件中。如果两个命令尝试将输出完全准确地写入文件怎么办,它会崩溃还是不会崩溃?
如果您在append
(-a
)模式下使用tee ,则没有数据丢失的风险,但没有附加操作的文件系统(例如NFS)除外。在append
模式下,tee
打开带有O_APPEND
标志的文件。
$ echo 1 | strace tee -a /tmp/file 2>&1 | grep open | grep /tmp/file
openat(AT_FDCWD, "/tmp/file", O_WRONLY|O_CREAT|O_APPEND, 0666) = 3
来自man 2 openat
:
O_APPEND The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2). The modification of the file offset and the write operation are performed as a single atomic step.
其中的关键句是文件偏移量的修改和写操作是作为单个原子步骤执行的。保证write()
从哪个实例进行的每次调用tee
都将原子偏移量自动定位到文件末尾,然后写入数据。
该openat
手册页呢注意,使用的这种模式是不安全的NFS文件系统中(正如我前面提到的):
O_APPEND may lead to corrupted files on NFS filesystems if more than one process appends data to a file at once. This is be‐ cause NFS does not support appending to a file, so the client kernel has to simulate it, which can't be done without a race condition.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句