Skip to content

Instantly share code, notes, and snippets.

@kedarmhaswade
Last active December 18, 2015 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kedarmhaswade/5835704 to your computer and use it in GitHub Desktop.
Save kedarmhaswade/5835704 to your computer and use it in GitHub Desktop.
Truncation of a unix file from outside ...
/* Can we truncate a file from outside? */
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int main(int argc, char** argv) {
/* opens the given argv[1] and writes a statement to it every 5 seconds */
int fd;
if ((fd = open(argv[1], O_RDWR|O_CREAT)) == -1) {
printf("open error: %s\n", strerror(errno));
return 1;
}
char buf[15];
int i = 0;
while (i < 10) {
sprintf(buf, "statement: %3d\n", i++);
if (write(fd, buf, 15) < 0) {
printf("write error: %s\n", buf);
return 1;
}
printf("sleeping, truncate the file with something like 'cat /dev/null > argv[1]'\n");
sleep(5);
}
if (close(fd) < 0) {
printf("close error: %s\n", strerror(errno));
return 1;
}
return 0;
}
/* On Linux, you'll observe that a "hole will be created */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment