Skip to content

Commit

Permalink
feat(sys): add a new method spawn to spawn process
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Jan 6, 2024
1 parent 006c751 commit 22515fe
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
21 changes: 21 additions & 0 deletions examples/spawn.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env eco

local time = require 'eco.time'
local sys = require 'eco.sys'
local log = require 'eco.log'

local pid = sys.spawn(function()
log.info('sub process:')

while true do
log.info('sub:', time.now())
time.sleep(1)
end
end)

log.info('spawn a process:', pid)

while true do
log.info('parent:', time.now())
time.sleep(1)
end
44 changes: 44 additions & 0 deletions sys.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

#include <sys/sysinfo.h>
#include <sys/prctl.h>
#include <stdbool.h>
#include <signal.h>
#include <unistd.h>
Expand Down Expand Up @@ -131,6 +132,48 @@ static int eco_sys_exec(lua_State *L)
return 2;
}

static int eco_sys_spawn(lua_State *L)
{
pid_t pid;

luaL_checktype(L, 1, LUA_TFUNCTION);

pid = fork();
if (pid < 0) {
lua_pushnil(L);
lua_pushstring(L, strerror(errno));
return 2;
}

if (pid == 0) {
struct eco_context *ctx = eco_get_context(L);
int error;

prctl(PR_SET_PDEATHSIG, SIGKILL);

ev_break(ctx->loop, 0);

lua_getglobal(L, "eco");
lua_getfield(L, -1, "run");
lua_remove(L, -2);
lua_insert(L, 1);

error = lua_pcall(L, lua_gettop(L) - 1, 0, 0);
if (error) {
fprintf(stderr, "%s\n", lua_tostring(L, -1));
goto err;
}

ev_run(ctx->loop, 0);
err:
ev_default_destroy();
exit(0);
}

lua_pushinteger(L, pid);
return 1;
}

static int eco_sys_strerror(lua_State *L)
{
int no = luaL_checkinteger(L, 1);
Expand All @@ -145,6 +188,7 @@ static const luaL_Reg funcs[] = {
{"getppid", eco_sys_getppid},
{"kill", eco_sys_kill},
{"exec", eco_sys_exec},
{"spawn", eco_sys_spawn},
{"strerror", eco_sys_strerror},
{NULL, NULL}
};
Expand Down

0 comments on commit 22515fe

Please sign in to comment.