2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 -- GNU General Public License for more details.
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 POSIX support functions for Lua
27 #include <sys/types.h>
38 /* Daemonization support */
40 static int daemonize(lua_State *L)
47 lua_pushboolean(L, 0);
48 lua_pushstring(L, "already-daemonized");
52 /* Attempt initial fork */
53 if((pid = fork()) < 0)
56 lua_pushboolean(L, 0);
57 lua_pushstring(L, "fork-failed");
62 /* We are the parent process */
63 lua_pushboolean(L, 1);
64 lua_pushnumber(L, pid);
68 /* and we are the child process */
71 /* We failed to become session leader */
72 /* (we probably already were) */
73 lua_pushboolean(L, 0);
74 lua_pushstring(L, "setsid-failed");
78 /* Close stdin, stdout, stderr */
83 /* Final fork, use it wisely */
87 /* Show's over, let's continue */
88 lua_pushboolean(L, 1);
95 char *facility_strings[] = { "auth",
116 int facility_constants[] = {
141 The parameter ident in the call of openlog() is probably stored as-is.
142 Thus, if the string it points to is changed, syslog() may start
143 prepending the changed string, and if the string it points to ceases to
144 exist, the results are undefined. Most portable is to use a string
148 char* syslog_ident = NULL;
150 int syslog_open(lua_State* L)
152 int facility = luaL_checkoption(L, 2, "daemon", &facility_strings);
153 facility = facility_constants[facility];
155 luaL_checkstring(L, 1);
160 syslog_ident = strdup(lua_tostring(L, 1));
162 openlog(syslog_ident, LOG_PID, facility);
166 char *level_strings[] = {
174 int level_constants[] = {
182 int syslog_log(lua_State* L)
184 int level = luaL_checkoption(L, 1, "notice", &level_strings);
185 level = level_constants[level];
187 luaL_checkstring(L, 2);
189 syslog(level, "%s", lua_tostring(L, 2));
193 int syslog_close(lua_State* L)
204 int luaopen_util_pposix(lua_State *L)
208 lua_pushcfunction(L, daemonize);
209 lua_setfield(L, -2, "daemonize");
211 lua_pushcfunction(L, syslog_open);
212 lua_setfield(L, -2, "syslog_open");
214 lua_pushcfunction(L, syslog_close);
215 lua_setfield(L, -2, "syslog_close");
217 lua_pushcfunction(L, syslog_log);
218 lua_setfield(L, -2, "syslog_log");