I have a sandbox on my server where I allow users to run their own PHP scripts. If a PHP script has an infinite loop, it only stops when Apache times the process out (30 seconds) which is obviously less than ideal. I know some web hosts automatically kill a PHP script consuming too much CPU for too long. How do I implement something like this at the server level in Linux, but without killing PHP processes that just take a long time (with sleep statements, or waiting for network latency, for example)?
And as a bonus question, how do I do the same with memory usage? I know PHP has built in memory limits, but included in this sandbox is a PHP extension that doesn't implement these limits until control returns back to PHP, at which time if the process went over the limit it's killed, but by then it's too late. It could have swapped out the entire swap disk in the meantime, bringing the server to a crawl.