Is it possible to have file removed upon process exit?

Kostik Belousov kostikbel at gmail.com
Sat Nov 27 19:22:15 UTC 2010


On Sat, Nov 27, 2010 at 05:07:15PM -0200, Carlos A. M. dos Santos wrote:
> On Sat, Nov 27, 2010 at 3:18 PM, Dimitry Andric <dim at freebsd.org> wrote:
> > On 2010-11-25 21:14, Xin LI wrote:
> >>
> >> For certain applications it is sometimes desirable to (e.g. for unix
> >> domain sockets) have file removed when the process quit, regardless
> >> whether the process is quit cleanly.  Is there a clean way to do this?
> >
> > Maybe your process could be the child of a parent which cleans up
> > afterwards?  (This is an analogy from real life. ;)
> 
> #include <stdio.h>
> #include <stdlib.h>
> #include <unistd.h>
> #include <sys/types.h>
> #include <sys/wait.h>
> 
> static char filename[] = "/tmp/tmpfXXXXXX";
> static int fd = 0;
> 
> int main(void) {
> 	if ((fd = mkstemp(filename)) >= 0) {
> 		pid_t pid;
> 		if ((pid = fork()) > 0) {
> 			/* parent */
> 			wait(NULL);
> 			printf("unlinking '%s'\n", filename);
> 			unlink(filename);
> 			return EXIT_SUCCESS;
> 		} else {
> 			/* child */
> 			printf("file name is '%s'\n", filename);
> 			sleep(10);
> 			abort();
> 		}
> 	}
> 	return EXIT_FAILURE;
> }
This approach has usual problems of making a mess if the program
want to fork() for other reasons, since the child should continue
to execute a logic in your case, but cannot wait for already forked
processes.

Usual advice is to have child monitoring the liveness of the parent.
You can either create a pipe before fork and read(2) from it in child,
never writing from parent. read(2) will return when parent exits.
Or, periodically compare getppid() with 1 in child, and do the cleanup
when equal.

Usually, it is too much hassle to do any of the tricks, normal
system cleanup of /tmp on reboot is good enough.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-hackers/attachments/20101127/3102cd3d/attachment.pgp


More information about the freebsd-hackers mailing list