如何强制执行 Lua 脚本运行时限制? [英] How to enforce Lua scripts runtime limit?

查看:44
本文介绍了如何强制执行 Lua 脚本运行时限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 lua 中用 dofile 运行一个几乎微不足道的脚本,在这台机器上运行 10000 次大约需要 52 秒,但是如果我运行 10000 次lua52 script.lua",则需要 3 到 4 倍.我知道涉及更多的系统调用和其他开销,但我试图实现的是运行脚本,超时时间为 3 秒,然后打印输出.我的问题是带有无限循环的脚本,无论是否有意,例如:

Running an almost trivial script in lua with dofile, 10000 times, takes about 52 seconds in this machine, but if i run 10000 times "lua52 script.lua", it takes 3 or 4 times more. I'm aware that there's more system calls involved and other overhead, but what i try to achieve is running scripts with a timeout of let's say 3 seconds, and print out the output. My problem is scripts with infinite loops, intentional or not, for example:

while(true) do
end

我可以在 Lua 中为 dofile 设置超时吗?每次使用 timeout(3) 调用解释器是我唯一的选择吗?

Can i make a timeout for a dofile from within Lua? Is my only option to call the interpreter each time with timeout(3)?

推荐答案

像我这样的新手在 Lua 问题上纠正 lhf 感觉有点不对,但这里是;将 "count" 传递给 debug.sethook 与传递 "c" 或 "call" 相同,在 n VM 指令之后传递以触发关联函数的正确掩码是 "".

It feels a bit wrong for a novice like me to be correcting lhf on Lua matters, but here goes; passing "count" to debug.sethook is the same as passing "c" or "call", the correct mask to pass to fire the associated function after n VM instructions is "".

因此,要限制从 dofile() 加载的代码的运行时间,请使用以下内容:

As such, to restrict the runtime of code loaded from dofile(), use something like the following:

local f = function() error("timeout") end
local x,y = xpcall(function()
  debug.sethook(f, "", 1e8)
  local ret = dofile("script.lua")
  debug.sethook()
  return ret
end, debug.traceback)

这篇关于如何强制执行 Lua 脚本运行时限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆