Lua fork 并发进程

标签 lua fork

我想从 lua 脚本同时执行后台进程

喜欢:

a = io.popen("deploy.exp" .. ip1):read("*a")
b = io.popen("deploy.exp" .. ip2):read("*a")

其中 a、b 是持续运行的进程。当我按照上面的方法执行此操作时,b 仅在 a 完成后才会运行。而deploy.exp脚本是一个expect脚本,用于ssh一些服务器,并执行一些命令。然后我需要从 a 和 b 中获取一些文本。对此有什么想法吗?我尝试使用 ExtensionProposal API。当我尝试这样做时,我收到一条错误消息:“* glibc detector free(): invalid next size (fast): 0x08aa2300 * * 中止”。

部分代码为

for k,v in pairs(single) do
command =  k .. " 1 " ..  table.concat(v, " ")
local out = io.pipe()
local pro = assert(os.spawn("./spaw.exp " .. command,{
      stdout = out,  
}))
if not proc then error("Failed to aprogrinate! "..tostring(err)) end
print(string.rep("#", 50))
local exitcode = proc:wait()
end

有人对此有任何经验(或建议/我们应该在哪里寻找)吗?或者给我一个 sample ?谢谢

顺便说一句:我尝试了 luaposix,但我找不到 posix.fork() 的任何样本。有谁可以分享一份吗? TKS

最佳答案

posix.fork() 是 luaposix library 的一部分,可以通过 luarocks 安装。它的工作方式与 fork(3) 大致相同。 ;它创建父进程的副本,并且它们都将执行调用 fork() 后的所有内容。子进程中 fork() 的返回值为 0,否则为刚刚生成的子进程的 PID。这是一个人为的示例:

local posix = require "posix"
local pid = posix.fork()

if pid == 0 then 
  -- this is the child process
  print(posix.getpid('pid') .. ": child process")

else 
  -- this is the parent process
  print(posix.getpid('pid') .. ": parent process")

  -- wait for the child process to finish
  posix.wait(pid) 

end

-- both processes get here
print(posix.getpid('pid') .. ": quitting")

这应该输出如下内容:

$ lua fork.lua 
27219: parent process
27220: child process
27220: quitting
27219: quitting

关于Lua fork 并发进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13228200/

相关文章:

linux - 子进程互相等待

c++ - 在 C 中制作一个基本的 shell 并且在管道/ fork 方面遇到麻烦

git - 如何恢复 merge 到我 fork 的仓库的 pull 请求,而不是 merge 到我的该仓库副本

lua - 如何使大嵌套 'for loops'循环更紧凑?有什么解决办法吗?

c++ - Lua DLL 库依赖

mysql - 使用 Lua 连接到 MySQL 数据库

string - Lua:String.match vs String.gmatch?

perl - 为什么包含 fork() 调用会产生更多循环

c - 至未签名并返回 : Casting Pointer vs Casting Dereference

用C程序调用linux命令cmp