in reply to Wait for CGI script to complete

The browser does not wait for such long and it throws an "Internal Server error"

No, the server doesn't wait for such a long time. For solution, read Watching long processes through CGI (Aug 02)