3

Is there a way to write-open files on Linux in C/C++ application in such a way that if the application is killed the open files will be discarded?

The application can be killed by SIGKILL so I cannot use signal handler.

tshepang
  • 12,111
  • 21
  • 91
  • 136
jackhab
  • 17,128
  • 37
  • 99
  • 136
  • With discarded you mean deleted (removed) from the file system? – Harald Jan 26 '14 at 17:18
  • Likely not possibly within the process itself. Is it important that the files while being written already have the correct name. If not, you could write them with a temporary name. Should the process survive until the `close()`, rename the file then. How you get rid of the temporary files if the process gets killed is a matter of how urgent you want to do it: regular cleanup cron, parent-process which notices that the sub-process is dead and cleans up after it. – Harald Jan 26 '14 at 17:27

1 Answers1

1

The typical trick for temporary files is to open/create a file, then unlink it without closing the file descriptor.

You end up with a file descriptor to a file which no longer exists. You can still read from it and write to it, but as soon as you close the file descriptor (or are killed) the file will be removed and the space it occupied is freed.

Of course, that doesn't really work if you decide you want to keep the file afterwards.

Kristof Provost
  • 26,018
  • 2
  • 26
  • 28
  • Can't one use `link("/proc/self/fd/n", "permanent-name");` if one wants to keep the file? – Ben Voigt Jan 26 '14 at 18:02
  • @BenVoigt Normally, that link would (illegaly) cross file system boundaries. Is that a special case? – Jonas Schäfer Jan 26 '14 at 18:13
  • @Jonas: After further research, apparently not. `proc/./fd` are special cases, they are symlinks that don't break when the target is deleted. But `link` isn't smart enough to relink the target. Perhaps there's some other function that is? – Ben Voigt Jan 26 '14 at 18:14
  • @Jonas: Actually, that question gives the answer. `linkat` with the `AT_FDCWD` and `AT_EMPTY_PATH` flag. See also http://comments.gmane.org/gmane.linux.file-systems/76553 – Ben Voigt Jan 26 '14 at 18:21
  • I cannot find any supporting material in my manpages, sadly. But yep, I saw the answer only after commenting here! – Jonas Schäfer Jan 26 '14 at 18:24