lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Egor Skriptunoff once stated:
> 
> Of course, in some situations it may be very useful to apply time
> constraint on some Lua code (especially code containing pattern functions,
> "while" loops, recursion, etc.) IMO, more correct way to achieve this is
> to introduce new function time_restricted_pcall(max_CPU_time, func, args)
> instead of hard-coding such limitations.

  If the code was purely Lua, then time_restricted_pcall() would be easily
written.  However, if any calls to C are made, then it gets complicated and
requires system specific code to handle.  On a POSIX system, I can see two
solutions, neither one decent.

  First solution: setitimer().  But this also involves catching SIGALRM and
it's considered bad form for a library to catch signals [1].  This is
especially true for SIGALRM as there can be only one outstanding interval
timer in a process.  Also, signals are just very nasty to work with (the
hardest bugs I've had to debug have always dealt with signals) and can
interact wierdly with code [3].

  Second solution: setrlimit().  We can limit the amount of CPU time we use. 
But this too, requires a signal handler, SIGXCPU or else if the process
exceeds the CPU time, it's terminated.  A library routine catching SIGXCPU
might be less of an issue than catching SIGALARM but there's still a
potential bug---setrlimit() is not an asynchronous-safe function, meaning
it's not safe to call it from a signal handler, and we *have* to call it
from the SIGXCPU signal handler or else our process goes bye-bye as it
exceeded its allowable CPU limit.

  -spc (It's not an easy problem ... )

[1]	The least of which is it violates the rule of least surprise [2]. If
	a library catches, say, SIGPIPE, that might cause issues if the
	programmer is unaware of that and attempts to catch SIGPIPE
	elsewhere.  The programmer than ends up with a confusing set of
	bugs.

[2]	http://www.catb.org/~esr/writings/taoup/html/ch01s06.html#id2878339

[3]	I had to write a signal handler in C [4] because I couldn't get it
	working as I wanted in Lua.  Here's the main comment from the C
	code:

		This entire file exists *because* I can't properly handle
		SIGCHLD in the server process.  What I want to do is just
		get the reason for a handler process terminating, but not
		wanting to deal with EINTR, so I set the handler to restart
		system calls.  But while I can do that in Lua, the Lua
		signal handler doesn't get control until the Lua VM gets
		control, and if we're sitting in a system call, that might
		take some time.  So, we do this in C, which can get the job
		done.

[4]	gopher://gopher.conman.org/0Gopher:Src:reapchild.c