Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have written a cgi script that needs some temporary files. Since the file needs to be passed off to a back-end executable, I cannot simple create the file and then unlink it to be sure the disk space is freed when the process dies.

I wrote a simple temporary file module that creates a unqiue temporary directory and then creates the temporary files inside. I used and END block to make sure the files where deleted when the script ended or died.

The problem is that it some cases, the END block is not executed and the files remain. When this first happened, I realized it was a result of the user stopping the http connection. A TERM or PIPE signal is sent to the cgi process.

I started installing signal handlers to catch the signals.

This has not completely solved the problem. In some cases, the http connection times out. The cgi process ends, but the END block in the temporary module is not executed. I tried installing signal handlers for all signals, but it did not help.

Does anyone know what happens to a cgi process when the http connection times-out? The web server in Apache on Linux.

Replies are listed 'Best First'.
Re: CGI Perl Script fails to clean-up
by lhoward (Vicar) on May 23, 2000 at 06:17 UTC
    A few solutions come to mind. My suggestions here tend to be "stepping around" the problem instead of actually fixing it:
    • make the back-end executable responsible for removing the temporary files.
    • You can unlink the temp file as soon as the "back-end process" has opened it and everything should work properly. You don't need to wait for the back-end process to complete (unless it does something funky like open the file multiple times). See the earlier discussion on Avoiding a Race Condition for more details about the "deleting an opened file" technique.
      Please look at my replies to an article on file locking at http://www.perlmonks.com/index.pl?node_id=7058, which explains some better ways to lock files and avoid a race condition than simply using flock() on a data file.

      Cheers,
      KM