Question: So this is as much a theoretical question as a language-specific one, but consider this:

I need PHP to execute a rather system-intensive process (using PHP `exec();`) that will be running in the background, but then when a user leaves that specific page, the process will be killed. 

I quickly realized that a dead man's switch would be an easy way to implement this since I'm not making use of any session variables or other server-side variables, which could end up looking like:

```
if($_SERVER['REQUEST_URI'] !== 'page_with_session.php'){
    //Instead of 'session_destroy();' this would be used to kill said process
}

```

In any case, a while loop in PHP, resetting a timer in a Python script or re-calling said script every 15 seconds so that it doesn't get to the end and kill the process. However, when the user leaves the page, the script will have been called but not able to reset before killing the process.

Are there any gaping holes in this idea? If not, how would the implementation in PHP/JS look? The order I see it working in would be:

1. Page is hit by user
2. `<?php exec('killer.py') ?>`
3. killer.py:
	1. Listen for 20 seconds - If no response...
	2. `os.system('pkill process')`
4. `<?php while(true){sleep(15); exec('killer.py no_wait_dont');} ?>`

Any thoughts you guys have would be greatly appreciated!

Mason

Answer: 
Javascript is a lot easier, and about as safe (that is, not much).

Just write a javascript ping function that, once every 10 seconds, posts something to ping.php (via ajax). This ping.php would log when the last ping was received in the user session (say in `$_SESSION['last_ping']`)

You can check for user activity from other pages by comparing `$_SESSION['last_ping']` to the current time. You would have to pepper your runtime-intensive pages with this, but it would certainly work.
Implement a heartbeat in JS. If it stops for more than a certain time then kill the subprocess:

* js sends a request
* php/python start the subprocess in a background and return pid to js
* js pings php/python with given pid
* php/python signals the subprocess corresponding to pid via IPC e.g., by sending SIGUSR1
* if subprocess doesn't receive a signal in time; it dies i.e., there is a constant self-destruct countdown in the subprocess

If you can't add the self-destruct mechanism to the subprocess then you need a watcher process that would receive signals and kill the subprocess. It is less reliable because you need to make sure that the watcher process is running.