MCPcopy Create free account
hub / github.com/bitcoin/bitcoin / fork_daemon

Function fork_daemon

src/bitcoind.cpp:53–110  ·  view source on GitHub ↗

Custom implementation of daemon(). This implements the same order of operations as glibc. * Opens a pipe to the child process to be able to wait for an event to occur. * * @returns 0 if successful, and in child process. * >0 if successful, and in parent process. * -1 in case of error (in parent process). * * In case of success, endpoint will be one end of a pipe f

Source from the content-addressed store, hash-verified

51 * which can be used with TokenWrite (in the child) or TokenRead (in the parent).
52 */
53int fork_daemon(bool nochdir, bool noclose, TokenPipeEnd& endpoint)
54{
55 // communication pipe with child process
56 std::optional<TokenPipe> umbilical = TokenPipe::Make();
57 if (!umbilical) {
58 return -1; // pipe or pipe2 failed.
59 }
60
61 int pid = fork();
62 if (pid < 0) {
63 return -1; // fork failed.
64 }
65 if (pid != 0) {
66 // Parent process gets read end, closes write end.
67 endpoint = umbilical->TakeReadEnd();
68 umbilical->TakeWriteEnd().Close();
69
70 int status = endpoint.TokenRead();
71 if (status != 0) { // Something went wrong while setting up child process.
72 endpoint.Close();
73 return -1;
74 }
75
76 return pid;
77 }
78 // Child process gets write end, closes read end.
79 endpoint = umbilical->TakeWriteEnd();
80 umbilical->TakeReadEnd().Close();
81
82#if HAVE_DECL_SETSID
83 if (setsid() < 0) {
84 exit(1); // setsid failed.
85 }
86#endif
87
88 if (!nochdir) {
89 if (chdir("/") != 0) {
90 exit(1); // chdir failed.
91 }
92 }
93 if (!noclose) {
94 // Open /dev/null, and clone it into STDIN, STDOUT and STDERR to detach
95 // from terminal.
96 int fd = open("/dev/null", O_RDWR);
97 if (fd >= 0) {
98 bool err = dup2(fd, STDIN_FILENO) < 0 || dup2(fd, STDOUT_FILENO) < 0 || dup2(fd, STDERR_FILENO) < 0;
99 // Don't close if fd<=2 to try to handle the case where the program was invoked without any file descriptors open.
100 if (fd > 2) close(fd);
101 if (err) {
102 exit(1); // dup2 failed.
103 }
104 } else {
105 exit(1); // open /dev/null failed.
106 }
107 }
108 endpoint.TokenWrite(0); // Success
109 return 0;
110}

Callers 1

AppInitFunction · 0.85

Calls 6

TakeReadEndMethod · 0.80
TakeWriteEndMethod · 0.80
TokenReadMethod · 0.80
TokenWriteMethod · 0.80
MakeFunction · 0.70
CloseMethod · 0.45

Tested by

no test coverage detected