Date: Sat, 27 Nov 2010 21:21:51 +0200 From: Kostik Belousov <kostikbel@gmail.com> To: "Carlos A. M. dos Santos" <unixmania@gmail.com> Cc: FreeBSD-Hackers <freebsd-hackers@freebsd.org>, Dimitry Andric <dim@freebsd.org>, d@delphij.net Subject: Re: Is it possible to have file removed upon process exit? Message-ID: <20101127192151.GL2392@deviant.kiev.zoral.com.ua> In-Reply-To: <AANLkTikH_uD1-yUe6KTufBvs9zRdQ%2BiMVQWcavBYRXU9@mail.gmail.com> References: <4CEEC3BD.3080204@delphij.net> <4CF13D7A.4060904@FreeBSD.org> <AANLkTikH_uD1-yUe6KTufBvs9zRdQ%2BiMVQWcavBYRXU9@mail.gmail.com>
next in thread | previous in thread | raw e-mail | index | archive | help
[-- Attachment #1 --]
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@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.
[-- Attachment #2 --]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (FreeBSD)
iEYEARECAAYFAkzxWk8ACgkQC3+MBN1Mb4hFRACg24LrAWKaYm+Zln4xRowBI4ey
1sgAoNUUGfzBVfoWHJHLQUxiGv+0sU6M
=5nIm
-----END PGP SIGNATURE-----
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20101127192151.GL2392>
