Skip to content

Commit

Permalink
Reimplement daemonize() without using daemon()
Browse files Browse the repository at this point in the history
The daemon() helper function is widely implemented, but is not really
standardized and is actually somewhat buggy on some platforms.

Implementing the desired functionality is also not all that complicated.

So, do it ourselves.

Closes: gh-161
  • Loading branch information
yoe committed Aug 6, 2024
1 parent 99cb654 commit 88d2267
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions nbd-server.c
Original file line number Diff line number Diff line change
Expand Up @@ -3779,18 +3779,24 @@ void setup_servers(GArray *const servers, const gchar *const modernaddr,

/**
* Go daemon (unless we specified at compile time that we didn't want this)
* @param serve the first server of our configuration. If its port is zero,
* then do not daemonize, because we're doing inetd then. This parameter
* is only used to create a PID file of the form
* /var/run/nbd-server.<port>.pid; it's not modified in any way.
**/
#if !defined(NODAEMON)
void daemonize() {
FILE*pidf;

if(daemon(0,0)<0) {
err("daemon");
}
pid_t child=fork();
if(child < 0) {
err("fork");
} else if(child > 0) {
exit(EXIT_SUCCESS);
} else {
if(setsid() < 0) {
err("setsid");
}
}
if(chdir("/")<0) {
err("chdir");
}
if(!*pidfname) {
strncpy(pidfname, "/var/run/nbd-server.pid", 255);
}
Expand All @@ -3802,9 +3808,28 @@ void daemonize() {
perror("fopen");
fprintf(stderr, "Not fatal; continuing");
}
int newfd;
if((newfd = open("/dev/null", O_RDWR)) < 0) {
err("open");
}
if(dup2(0, newfd) < 0) {
err("dup2 stdin");
}
if(dup2(1, newfd) < 0) {
err("dup2 stdout");
}
if(dup2(2, newfd) < 0) {
err("dup2 stderr");
}
child=fork();
if(child < 0) {
err("fork");
} else if(child > 0) {
exit(EXIT_SUCCESS);
}
}
#else
#define daemonize(serve)
#define daemonize()
#endif /* !defined(NODAEMON) */

/*
Expand Down

0 comments on commit 88d2267

Please sign in to comment.