I'm not a cgi guru, but until one answers you, you will probably need to set up a session, see Creating Sessions. A pure socket connection can detect a client disconnect, but a web server won't do that, as far as I know.
I don't think that's an option, because I need to check the user state periodically, and the only way I can think of doing something similar via sessions is to set session expiry time. And that's not exactly what I am looking for...