Reputation: 311
I want to execute multiple processes concurrently from a lua script e.g.
os.execute("cmd1")
os.execute("cmd2")
os.execute("cmd3")
where cmd1,2 and 3 are continually running processes. When i do this as above, cmd2 and 3 will only run when cmd1 is finished. Any idea on this? Should i be using "fork" or something equivalent?
Thanks in advance
Upvotes: 2
Views: 5784
Reputation: 5149
(answer mostly copied from Call popen with environment)
There is an os.spawn
function in the ExtensionProposal API.
You can use it as follows:
require"ex"
local proc, err = os.spawn{
command = e.."/bin/aprogr",
args = {
"arg1",
"arg2",
-- etc
},
env = {
A = 100, -- I assume it tostrings the value
B = "Hi",
C = "Test",
},
-- you can also specify stdin, stdout, and stderr
-- see the proposal page for more info
}
if not proc then
error("Failed to aprogrinate! "..tostring(err))
end
-- if you want to wait for the process to finish:
local exitcode = proc:wait()
lua-ex-pai provides implementations for POSIX and Windows. It allows the spawning of multiple concurrent processes.
You can find precompiled binaries of this implementation bundled with the LuaForWindows distribution.
Here is a more concise version of your use case:
require"ex"
local cmd1_out = io.pipe()
local cmd1_proc = assert(os.spawn("cmd", {
stdout = cmd1_out,
}))
local cmd2_out = io.pipe()
local cmd2_proc = assert(os.spawn("cmd", {
stdout = cmd1_out,
}))
-- perform actions with cmd1 and cmd2
Upvotes: 3
Reputation: 52641
Try simply adding & at the end of your commands:
os.execute("cmd1 &")
os.execute("cmd2 &")
os.execute("cmd3 &")
This should work on an operative system. On windows there might be a way to to the same, but I have no idea of what it is.
Upvotes: 2
Reputation: 9549
You've got several solutions to your problem:
&
to put tasks into the background. For example: os.execute('(sleep 10&& echo bar) & echo foo')
posix.fork()
functionUpvotes: 5
Reputation: 57545
That's because Lua is single threaded. To run it concurrently you'll need to provide a multi-threaded solution for Lua (not coroutines, because they're microthreads!), like lua pthreads.
Upvotes: 2