Skip to content

Commit 7a3b28a

Browse files
committed
Implemented portable daemonize function for win and mac
1 parent 1a1fcdb commit 7a3b28a

File tree

4 files changed

+32
-2
lines changed

4 files changed

+32
-2
lines changed

src/sys/sig.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,35 @@ void XUtils_ErrExit(const char * pFmt, ...)
6565
exit(EXIT_FAILURE);
6666
}
6767

68+
int XUtils_Daemonize(int bNoChdir, int bNoClose)
69+
{
70+
#ifdef __linux__
71+
return daemon(bNoChdir, bNoClose);
72+
#else
73+
pid_t pid = fork();
74+
if (pid < 0) return -1;
75+
if (pid > 0) exit(0); // parent exits
76+
77+
if (setsid() < 0) return -1;
78+
79+
pid = fork();
80+
if (pid < 0) return -1;
81+
if (pid > 0) exit(0);
82+
83+
umask(0);
84+
if (!bNoChdir) chdir("/");
85+
86+
if (!bNoClose)
87+
{
88+
freopen("/dev/null", "r", stdin);
89+
freopen("/dev/null", "w", stdout);
90+
freopen("/dev/null", "w", stderr);
91+
}
92+
#endif
93+
94+
return 0;
95+
}
96+
6897
void XSig_Callback(int nSig)
6998
{
7099
/* Handle signals */

src/sys/sig.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ typedef void(*xsig_cb_t)(int);
2121

2222
void XUtils_Backtrace(void);
2323
void XUtils_ErrExit(const char *pFmt, ...);
24+
int XUtils_Daemonize(int bNoChdir, int bNoClose);
2425

2526
#define errex(...) XUtils_ErrExit(XLOG_THROW_LOCATION __VA_ARGS__)
2627

src/xver.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
#define XUTILS_VERSION_MAX 2
1414
#define XUTILS_VERSION_MIN 6
15-
#define XUTILS_BUILD_NUMBER 44
15+
#define XUTILS_BUILD_NUMBER 45
1616

1717
#ifdef __cplusplus
1818
extern "C" {

tools/xtop.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1597,7 +1597,7 @@ int main(int argc, char *argv[])
15971597
return XSTDERR;
15981598
}
15991599

1600-
if (args.bDaemon && daemon(XTRUE, XTRUE) < 0)
1600+
if (args.bDaemon && XUtils_Daemonize(XTRUE, XTRUE) < 0)
16011601
{
16021602
xlogn("Failed to run server as daemon: %d", errno);
16031603
return XSTDERR;

0 commit comments

Comments
 (0)