锁定老帖子 主题:做一个彻底干净的sandbox
精华帖 (0) :: 良好帖 (6) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-02-18
最后修改:2009-02-18
有时候,我们想要提供一个清洁的环境运行一些不太可信任的代码: Thread.new do $SAFE = 4 eval some_string end
我们也可以用Thread#kill或者Thread#kill!终止它
-----------------------------------------------------------------------------------------------------------------------------------------------
#drbsvr.rb require 'drb' require "drb/acl" module EvalServer class << self def __eval__ str begin res = eval str @__err__ = nil return res rescue Exception => ex @__err__ = ex.message nil end end def __get_error__ @__err__ end end end #deny all other connection except local call __acl__ = ACL.new( %w[ deny all allow localhost] ) DRb.install_acl(__acl__) DRb.start_service("druby://:14194", EvalServer) DRb.thread.join
不能用fork,系统不支持。 也不能用system()——那样会产生一个cmd窗口 (那就不是"后台进程"了)。 #... #stdin, stdout, stderror are handles (Fixnum) def create_process(command, stdin, stdout, stderror) params = [ 'L', # IN LPCSTR lpApplicationName 'P', # IN LPSTR lpCommandLine 'L', # IN LPSECURITY_ATTRIBUTES lpProcessAttributes 'L', # IN LPSECURITY_ATTRIBUTES lpThreadAttributes 'L', # IN BOOL bInheritHandles 'L', # IN DWORD dwCreationFlags 'L', # IN LPVOID lpEnvironment 'L', # IN LPCSTR lpCurrentDirectory 'P', # IN LPSTARTUPINFOA lpStartupInfo 'P'] # OUT LPPROCESS_INFORMATION lpProcessInformation startupInfo = [STARTUP_INFO_SIZE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW, 0, 0, 0, stdin, stdout, stderror].pack('IIIIIIIIIIIISSIIII') processInfo = [0, 0, 0, 0].pack('IIII') command << 0 createProcess = Win32API.new("kernel32", "CreateProcess", params, 'I') raise_last_win_32_error if createProcess.call(0, command, 0, 0, 1, 0, 0, 0, startupInfo, processInfo).zero? hProcess, hThread, dwProcessId, dwThreadId = processInfo.unpack('LLLL') close_handle(hProcess) close_handle(hThread) [dwProcessId, dwThreadId] end
3.启动server并连接。 此处start_service容易引人误解,其实只是连接到server的准备工作而已。 Thread.new do create_process('ruby drbsvr.rb', 0, 0, 0) end DRb.start_service eval_svr = DRbObject.new(nil, "druby://localhost:14194")
eval_svr.__eval__ "little f*ck" puts eval_svr.__get_error__
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 1940 次