The short answer is that the text editor isn't holding the file open.
The longer answer is that a text editor is usually doing things with a bit more finesse than one might assume.
Let's look at the humble vim
editor.
For preparation, create a file called demo.txt
and add a couple of lines.
Now is the time
for all good men
Now use strace
to see what vi
is doing:
strace -frt -o myfile.txt vi demo.txt
Add a new line to the middle of the file, save and exit.
Here's what the key part of the strace
output looks like:
...
15850 0.000037 unlink("demo.txt~") = -1 ENOENT (No such file or directory)
15850 (1) 0.000034 rename("demo.txt", "demo.txt~") = 0
15850 (2) 0.000055 open("demo.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 3
15850 (3) 0.000044 write(3, "Now is the time\nadding a new lin"..., 51) = 51
15850 0.000042 fsync(3) = 0
15850 0.003511 stat("demo.txt", {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
15850 0.000039 stat("demo.txt", {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
15850 (4) 0.000033 close(3) = 0
15850 (5) 0.000029 chmod("demo.txt", 0100644) = 0
15850 0.000037 setxattr("demo.txt", "system.posix_acl_access", "\x02\x00\x00\x00\x01\x00\x06\x00\xff\xff\xff\xff\x04\x00\x04\x00\xff\xff\xff\xff \x00\x04\x00\xff\xff\xff\xff", 28, 0) = 0
15850 0.000091 write(1, " 3L, 51C written", 16) = 16
15850 0.000040 lseek(4, 0, SEEK_SET) = 0
15850 0.000029 write(4, "b0VIM 7.4\0\0\0\0\20\0\0\274\267\25_\324\35\6\0\352=\0\0myuser"..., 4096) = 4096
15850 0.000040 stat("/home/myuser/demo.txt", {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
15850 (6) 0.000046 unlink("demo.txt~") = 0
...
See what vim
is doing here, in very quick succession at time of save:
- Renaming the file to a backup file with trailing tilde (
demo.txt~
)
- Opening
demo.txt
in write mode as file descriptor 3
- Writing the new modified text.
- Closing the file (FD 3)
- Performing
chmod
and such on the new version of the file.
- Removing the scratch file.
All of these steps are done very quickly, only when the "write file" command is given.
You can edit a file in vim
and modify the file in a separate process, and vim
won't do anything about it until the time you try to save the file, at which point it will warn you.
Other editors are likely doing similar things. You can use strace
to see what kind of system calls they are making and correlate that with what you see in lsof
.