Implement daemon() using fork() for OSX

This commit is contained in:
Tatsuhiro Tsujikawa 2019-05-28 23:23:07 +09:00
parent 8d6ecd66cc
commit b0f5e5cc79
4 changed files with 46 additions and 2 deletions

View File

@ -435,7 +435,7 @@ int main(int argc, char **argv) {
#ifdef __sgi #ifdef __sgi
if (daemon(0, 0, 0, 0) == -1) { if (daemon(0, 0, 0, 0) == -1) {
#else #else
if (daemon(0, 0) == -1) { if (util::daemonize(0, 0) == -1) {
#endif #endif
perror("daemon"); perror("daemon");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);

View File

@ -1148,7 +1148,7 @@ int call_daemon() {
return 0; return 0;
} }
# endif // HAVE_LIBSYSTEMD # endif // HAVE_LIBSYSTEMD
return daemon(0, 0); return util::daemonize(0, 0);
#endif // !__sgi #endif // !__sgi
} }
} // namespace } // namespace

View File

@ -1542,6 +1542,46 @@ std::mt19937 make_mt19937() {
return std::mt19937(rd()); return std::mt19937(rd());
} }
int daemonize(int nochdir, int noclose) {
#if defined(__APPLE__)
pid_t pid;
pid = fork();
if (pid == -1) {
return -1;
} else if (pid > 0) {
_exit(EXIT_SUCCESS);
}
if (setsid() == -1) {
return -1;
}
pid = fork();
if (pid == -1) {
return -1;
} else if (pid > 0) {
_exit(EXIT_SUCCESS);
}
if (nochdir == 0) {
if (chdir("/") == -1) {
return -1;
}
}
if (noclose == 0) {
if (freopen("/dev/null", "r", stdin) == nullptr) {
return -1;
}
if (freopen("/dev/null", "w", stdout) == nullptr) {
return -1;
}
if (freopen("/dev/null", "w", stderr) == nullptr) {
return -1;
}
}
return 0;
#else // !defined(__APPLE__)
return daemon(nochdir, noclose);
#endif // !defined(__APPLE__)
}
} // namespace util } // namespace util
} // namespace nghttp2 } // namespace nghttp2

View File

@ -772,6 +772,10 @@ StringRef extract_host(const StringRef &hostport);
// Returns new std::mt19937 object. // Returns new std::mt19937 object.
std::mt19937 make_mt19937(); std::mt19937 make_mt19937();
// daemonize calls daemon(3). If __APPLE__ is defined, it implements
// daemon() using fork().
int daemonize(int nochdir, int noclose);
} // namespace util } // namespace util
} // namespace nghttp2 } // namespace nghttp2