C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 从C API调用的Lua脚本的执行时间限制大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
luaL_loadfile(mState,path.c_str());
lua_pcall(mState,0);

有没有办法为这两个C语句设置执行时间限制(例如10-20秒),然后加载然后执行lua文件

由于Lua文件不受信任,我不希望恶意用户无限期地使用Lua代码中的无限循环挂起程序.

标记C,因为Lua API是C,标记C,因为我使用C

解决方法

有lua_sethook可以用来告诉解释器在执行每个“count”指令后调用一个钩子.这样,您可以监视用户脚本并终止它,如果它占用了配额:
int lua_sethook (lua_State *L,lua_Hook f,int mask,int count);

这也可以从Lua使用:

debug.sethook(function() print("That's enough for today"); os.exit(0); end,"",10000)
for i=1,10000 do end

如果您使用http://lua-users.org/wiki/SandBoxes中的技术,那么您可以使用sethook()和完全从Lua完成的朋友设置安全的执行环境,然后在执行用户脚本时切换到沙箱模式.我在这里尝试过,只是为了开始:

-- set an execution quota 
local function set_quota(secs)
 local st=os.clock()
 function check() 
  if os.clock()-st > secs then 
    debug.sethook() -- disable hooks
    error("quota exceeded")
  end
 end
 debug.sethook(check,100000);
end

-- these are the global objects,the user can use:
local env = {print=print}

-- The user code is allowed to run for 5 seconds.
set_quota(5)

-- run code under environment:
local function run(untrusted_code)
  local untrusted_function,message = loadstring(untrusted_code)
  if not untrusted_function then return nil,message end
  setfenv(untrusted_function,env)
  return pcall(untrusted_function)
end

-- here is the user code:
local userscript=[[
function fib(n) 
 if n<2 then return n
 else return fib(n-2)+fib(n-1)
 end
end
for n=1,42 do print(n,fib(n)) end
]]
-- call it:
local r,m=run(userscript)
print(r,m)

这应该打印fib()的值5秒,然后显示错误.

大佬总结

以上是大佬教程为你收集整理的c – 从C API调用的Lua脚本的执行时间限制全部内容,希望文章能够帮你解决c – 从C API调用的Lua脚本的执行时间限制所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: