From 3349e674c3ee0c3c8bc063b2c3ab7af636949eda Mon Sep 17 00:00:00 2001 From: Tobias Ulmer Date: Tue, 12 Feb 2019 19:06:05 +0100 Subject: [PATCH] e2lib: implement forkpty Signed-off-by: Tobias Ulmer --- generic/e2lib.lua | 24 ++++++++++++++++++++++++ generic/le2lib.c | 25 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/generic/e2lib.lua b/generic/e2lib.lua index 9823787..aec3579 100644 --- a/generic/e2lib.lua +++ b/generic/e2lib.lua @@ -294,6 +294,30 @@ function e2lib.fork() return pid end +--- Forkpty. Like fork but open a PTY. +-- @return PID of child or false on error. PID of 0 means child process. +-- @return File Descriptor for pseudo terminal (parent only). +-- Error object on failure. +-- @return Path to PTY device node. +function e2lib.forkpty() + local rc, re + local pid, fdm, ptyname + + pid, fdm, ptyname = le2lib.forkpty() + if not pid then + return false, err.new("failed to fork new pty: %s", fdm) + end + if pid == 0 then + -- child, return early + return pid + end + + assert(type(fdm) == "number") + assert(type(ptyname) == "string") + + return pid, fdm, ptyname +end + --- Set umask value. -- @param mask New umask value. -- @return Previous umask value. diff --git a/generic/le2lib.c b/generic/le2lib.c index e5b0b7e..bac7f73 100644 --- a/generic/le2lib.c +++ b/generic/le2lib.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -884,6 +885,29 @@ signal_received(lua_State *L) return 2; } +static int +do_forkpty(lua_State *L) +{ + int cpid, fdm; + char ptyname[PATH_MAX]; + + cpid = forkpty(&fdm, ptyname, NULL, NULL); + if (cpid < 0) { + lua_pushboolean(L, 0); + lua_pushstring(L, strerror(errno)); + return 2; + } + + lua_pushnumber(L, cpid); + if (cpid == 0) + return 1; + + lua_pushnumber(L, fdm); + lua_pushstring(L, ptyname); + + return 3; +} + static luaL_Reg lib[] = { { "chdir", change_directory }, { "chmod", do_chmod }, @@ -893,6 +917,7 @@ static luaL_Reg lib[] = { { "execvp", do_execvp }, { "exists", file_exists }, { "fork", lua_fork }, + { "forkpty", do_forkpty }, { "getpid", do_getpid }, { "hardlink", do_hardlink }, { "kill", do_kill }, -- 2.39.5