However, sort file.txt -o file.txt is NOT safe. A strace sequence (sorting 1 2 3 4 5):
read(3, "1\n2\n3\n4\n5\n\n", 4096) = 11
read(3, "", 4096) = 0
_llseek(3, 0, [11], SEEK_CUR) = 0
close(3) = 0
munmap(0xb7743000, 4096) = 0
ftruncate64(1, 0) = 0 <---------------------- (*)
fstat64(1, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7743000
write(1, "\n1\n2\n3\n4\n5\n", 11) = 11
close(1) = 0
If at this time, the system crashes (or later at write), the data is gone forever (or have a suffering recovery). Should we warn users of this, or add special treatment with this case (write a temp file and rename it)?
Thank your for your attention.