in reply to Temporary files and cleaning up after an interruption

I was thinking of typical solutions for this problem:

Then a (perhaps novel) approach came to me.

You could spawn a child that deamonizes itself (so signals to the parent don't get sent to the child), ignores all the signals it can (so no need for signal handlers and the problems they cause in Perl), and then waits for the parent to exit.

Ah, but how does a child wait for a parent to exit? Well, just have the parent flock() the temporary file before creating the child and pass a handle for the temporary file to the child and the child can block on flock() waiting for the parent to close the file. If the parent dies suddenly, the operating system will still close the file, which releases the lock and causes the child to wake up and delete the file.

To prevent a race condition, I'd have the parent not even try to delete the file (otherwise a new invocation of the script might pick the same file name while a previous child is just getting around to deleting what it considers to be an old file). So in your case (of renaming the file), the parent should just create an extra link (though this makes the script less portable).

If you have trouble coding this, then let me/us know.

        - tye (but my friends call me "Tye")
  • Comment on (tye)Re: Temporary files and cleaning up after an interruption

Replies are listed 'Best First'.
Re: Temporary files and cleaning up after an interruption
by Dominus (Parson) on Jan 05, 2001 at 08:38 UTC
    Says tye:

    How does a child wait for a parent to exit? (use flock as an IPC mechanism)
    That's nice. Thanks for the idea.

    Here's an alternative mechanism. I think this might be more commonly used:

    #!/usr/bin/perl pipe R, W or die; die unless defined my $pid = fork; if ($pid) { # parent close R; print "parent: I'm going to do some work now\n"; for (1 .. rand 12) { print "Parent is working...\n"; sleep 1; } print "parent: exiting\n"; } else { # child close W; print "child: waiting for parent to exit\n"; <R>; print "child: parent exited; exiting\n"; }
    I used this technique extensively in my obfuscated contest entry.

      Says tye:

      How does a child wait for a parent to exit? (use flock as an IPC mechanism)

      Another related technique:

      # in the child: while (whatever...) { do_some_work(); if (getppid() == 1) { print "my parent is dead!"; clean_up(); exit; } }

        Yes, both of those work. I didn't use the first one because I already had a shared file handle so no need to create another one. I didn't use the second one because it doesn't allow me to wait; I have to loop sleeping and checking.

        But they are both good techniques to know. Thanks.

                - tye (but my friends call me "Tye")