diff --git a/lightningd/lightningd.c b/lightningd/lightningd.c index b716dbbfa..a34bbfdcb 100644 --- a/lightningd/lightningd.c +++ b/lightningd/lightningd.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +70,7 @@ static struct lightningd *new_lightningd(const tal_t *ctx, timers_init(&ld->timers, time_mono()); ld->topology = new_topology(ld, ld->log); ld->debug_subdaemon_io = NULL; + ld->daemon = false; return ld; } @@ -230,6 +233,24 @@ static void init_txfilter(struct wallet *w, struct txfilter *filter) } } +static void daemonize_but_keep_dir(void) +{ + /* daemonize moves us into /, but we want to be here */ + const char *cwd = path_cwd(NULL); + + if (!cwd) + fatal("Could not get current directory: %s", strerror(errno)); + if (!daemonize()) + fatal("Could not become a daemon: %s", strerror(errno)); + + /* Move back: important, since lightning dir may be relative! */ + if (chdir(cwd) != 0) + fatal("Could not return to directory %s: %s", + cwd, strerror(errno)); + + tal_free(cwd); +} + int main(int argc, char *argv[]) { struct log_book *log_book; @@ -331,6 +352,10 @@ int main(int argc, char *argv[]) /* Create RPC socket (if any) */ setup_jsonrpc(ld, ld->rpc_filename); + /* Now we're about to start, become daemon if desired. */ + if (ld->daemon) + daemonize_but_keep_dir(); + /* Mark ourselves live. */ log_info(ld->log, "Server started with public key %s, alias %s (color #%s) and lightningd %s", type_to_string(ltmp, struct pubkey, &ld->id), diff --git a/lightningd/lightningd.h b/lightningd/lightningd.h index e5cce9cb5..f0bc07ae4 100644 --- a/lightningd/lightningd.h +++ b/lightningd/lightningd.h @@ -77,6 +77,9 @@ struct lightningd { /* The directory to find all the subdaemons. */ const char *daemon_dir; + /* Are we told to run in the background. */ + bool daemon; + /* Our config dir, and rpc file */ char *config_dir; char *rpc_filename; diff --git a/lightningd/options.c b/lightningd/options.c index d26b46156..0bb98e831 100644 --- a/lightningd/options.c +++ b/lightningd/options.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -211,6 +212,8 @@ static char *opt_set_fee_rates(const char *arg, struct chain_topology *topo) static void config_register_opts(struct lightningd *ld) { + opt_register_noarg("--daemon", opt_set_bool, &ld->daemon, + "Run in the background, suppress stdout/stderr"); opt_register_arg("--ignore-fee-limits", opt_set_bool_arg, opt_show_bool, &ld->config.ignore_fee_limits, "(DANGEROUS) allow peer to set any feerate");