Around the web many people say you can truncate a file using > filename
or truncate -s0 filename
while file begin used
I know everytime a process write in a file, the process uses a offset for write in a file, doing a test with an script like this.
#!/usr/bin/env python
import os, time
with open("passwd","w") as f: #copy of passwd file in my current directory
f.seek(0)
for x in xrange(1,1000):
f.write("hello world \n" + time.ctime() + "\n")
f.flush()
time.sleep(2)
every time my script make a write syscall the offset in /proc/pid_number/fdinfo/3 pos
field is changed, but when i try to truncate the the file using the method listed above, in my file i see many characters like this ^@
when i open the file using vim
or less -u
and the file type is change from ASCII text
to data
and when i use ls -l filename
the size isn't changed
So, when truncate the file the offset of the file are not report back, i'm testing this in Centos 7
and in Redhat 5
, so i can tell changed the file size while the file is in use by processes doesn't free space and make dirty my file.
So my questions is, if my process has an opened file in pos 1000
and i did truncate -s0 filename
, if the truncate works, what happening in the next process write?
strace truncate -s0 passwd
open("passwd", O_WRONLY|O_CREAT|O_NONBLOCK, 0666) = 3
ftruncate(3, 0) = 0
close(3) = 0
close(1) = 0
close(2) = 0
exit_group(0) = ?
ls -l passwd
-rw-rw-r--. 1 user91 users 13832 Feb 23 17:16 passwd
As you can see my file wasn't truncated
This problem doesn't happen if i open the in append mode, for example with this code.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
int main(){
int range = 1000;
int x; x = open("passwd", O_WRONLY|O_CREAT|O_APPEND);
int i = 0;
for( i = 0; i <= range; range++)
write(x,"hello world\n",12);
sleep(2);
}