The answers already given are great. However, some web servers buffer output from CGI scripts (Apache hasn't buffered CGI output since 1.2, quite a while ago;). If you are still having a problem after , check your web server documentation for "non-parsed headers".
Also, remember that this is never guaranteed to work 100% of the time - connectivity can be lost, the user's computer can lose power, etc. etc. You may want to consider another way of communicating the results in addition to this. Maybe email, or another page to view status?
Good luck