2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
12 * POSIX support functions for Lua
15 #define MODULE_VERSION "0.3.0"
20 #include <sys/types.h>
31 /* Daemonization support */
33 static int lc_daemonize(lua_State *L)
40 lua_pushboolean(L, 0);
41 lua_pushstring(L, "already-daemonized");
45 /* Attempt initial fork */
46 if((pid = fork()) < 0)
49 lua_pushboolean(L, 0);
50 lua_pushstring(L, "fork-failed");
55 /* We are the parent process */
56 lua_pushboolean(L, 1);
57 lua_pushnumber(L, pid);
61 /* and we are the child process */
64 /* We failed to become session leader */
65 /* (we probably already were) */
66 lua_pushboolean(L, 0);
67 lua_pushstring(L, "setsid-failed");
71 /* Close stdin, stdout, stderr */
76 /* Final fork, use it wisely */
80 /* Show's over, let's continue */
81 lua_pushboolean(L, 1);
88 char *facility_strings[] = { "auth",
109 int facility_constants[] = {
134 The parameter ident in the call of openlog() is probably stored as-is.
135 Thus, if the string it points to is changed, syslog() may start
136 prepending the changed string, and if the string it points to ceases to
137 exist, the results are undefined. Most portable is to use a string
141 char* syslog_ident = NULL;
143 int lc_syslog_open(lua_State* L)
145 int facility = luaL_checkoption(L, 2, "daemon", &facility_strings);
146 facility = facility_constants[facility];
148 luaL_checkstring(L, 1);
153 syslog_ident = strdup(lua_tostring(L, 1));
155 openlog(syslog_ident, LOG_PID, facility);
159 char *level_strings[] = {
167 int level_constants[] = {
175 int lc_syslog_log(lua_State* L)
177 int level = luaL_checkoption(L, 1, "notice", &level_strings);
178 level = level_constants[level];
180 luaL_checkstring(L, 2);
182 syslog(level, "%s", lua_tostring(L, 2));
186 int lc_syslog_close(lua_State* L)
197 int lc_syslog_setmask(lua_State* L)
199 int level_idx = luaL_checkoption(L, 1, "notice", &level_strings);
203 mask |= LOG_MASK(level_constants[level_idx]);
204 } while (++level_idx<=4);
212 int lc_getpid(lua_State* L)
214 lua_pushinteger(L, getpid());
218 /* Register functions */
220 int luaopen_util_pposix(lua_State *L)
224 lua_pushcfunction(L, lc_daemonize);
225 lua_setfield(L, -2, "daemonize");
227 lua_pushcfunction(L, lc_syslog_open);
228 lua_setfield(L, -2, "syslog_open");
230 lua_pushcfunction(L, lc_syslog_close);
231 lua_setfield(L, -2, "syslog_close");
233 lua_pushcfunction(L, lc_syslog_log);
234 lua_setfield(L, -2, "syslog_log");
236 lua_pushcfunction(L, lc_syslog_setmask);
237 lua_setfield(L, -2, "syslog_setminlevel");
239 lua_pushcfunction(L, lc_getpid);
240 lua_setfield(L, -2, "getpid");
242 lua_pushliteral(L, "pposix");
243 lua_setfield(L, -2, "_NAME");
245 lua_pushliteral(L, MODULE_VERSION);
246 lua_setfield(L, -2, "_VERSION");