I have a textarea in my webpage in which the user is to paste a c program. At the server side, I save this code in a file appropriately. I use the shell_exec() function to call gcc to execute the c program. This works fine. And so does the execution part.
But what if the user (un)intentionally gives an infinite loop? When I use the function –
shell_exec("./a.out")
the program goes into an infinite loop. How do I break out of such a loop from the php script itself? Is there a way?
Use ulimit to limit the CPU usage? Note that this is per process, so if the user “forks” continually the process, you may be in trouble.
Another method would be to have a wrapper process that monitors and kills all it’s child processes, and let that start the a.out. It depends on whether you can trust your “clients” or not (e.g. are they your good friends, or is this a school project or a public website) – your paranoia level should increase by threat level.
If you want more refined security, run the process via ssh in a virtual machine. Then just kill the virtual machine after X seconds, and start a fresh one from a saved snapshot. (You could have a pool of VM’s ready to run, so the user don’t have to wait for the VM to load)