Comparison

util-src/pposix.c @ 586:b828d7d47973

Add posix support library, and adjust makefiles for it
author Matthew Wild <mwild1@gmail.com>
date Sat, 06 Dec 2008 23:20:59 +0000
child 588:e743cb742ca6
comparison
equal deleted inserted replaced
585:033817e12ddb 586:b828d7d47973
1 /* Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 --
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.
9 --
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.
14 --
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.
18 */
19
20 /* pposix.c
21 POSIX support functions for Lua
22 */
23
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <libgen.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30
31 #include "lua.h"
32
33 static int daemonize(lua_State *L)
34 {
35
36 pid_t pid;
37
38 if ( getppid() == 1 )
39 {
40 lua_pushboolean(L, 0);
41 lua_pushstring(L, "already-daemonized");
42 return 2;
43 }
44
45 /* Attempt initial fork */
46 if((pid = fork()) < 0)
47 {
48 /* Forking failed */
49 lua_pushboolean(L, 0);
50 lua_pushstring(L, "fork-failed");
51 return 2;
52 }
53 else if(pid != 0)
54 {
55 /* We are the parent process */
56 printf("We are the parent, pid of child is %d\n", (int)pid);
57 lua_pushboolean(L, 1);
58 lua_pushnumber(L, pid);
59 return 2;
60 }
61
62 printf("We are the child, pid reports %d\n", (int)pid);
63 /* and we are the child process */
64 if(setsid() == -1)
65 {
66 /* We failed to become session leader */
67 /* (we probably already were) */
68 lua_pushboolean(L, 0);
69 lua_pushstring(L, "setsid-failed");
70 return 2;
71 }
72
73 /* Close stdin, stdout, stderr */
74 /* close(0);
75 close(1);
76 close(2);
77 */
78 /* Final fork, use it wisely */
79 if(fork())
80 exit(0);
81
82 /* Show's over, let's continue */
83 lua_pushboolean(L, 1);
84 lua_pushnil(L);
85 return 2;
86 }
87
88 int luaopen_util_pposix(lua_State *L)
89 {
90 lua_newtable(L);
91 lua_pushcfunction(L, daemonize);
92 lua_setfield(L, -2, "daemonize");
93 return 1;
94 };