Is it possible to have file removed upon process exit?

Carlos A. M. dos Santos unixmania at gmail.com
Sat Nov 27 19:07:16 UTC 2010


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;
}


More information about the freebsd-hackers mailing list