]>
git.proxmox.com Git - ceph.git/blob - ceph/src/common/Preforker.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 #ifndef CEPH_COMMON_PREFORKER_H
4 #define CEPH_COMMON_PREFORKER_H
8 #include <sys/socket.h>
16 #include "include/assert.h"
17 #include "common/safe_io.h"
18 #include "common/errno.h"
21 * pre-fork fork/daemonize helper class
23 * Hide the details of letting a process fork early, do a bunch of
24 * initialization work that may spam stdout or exit with an error, and
25 * then daemonize. The exit() method will either exit directly (if we
26 * haven't forked) or pass a message to the parent with the error if
32 int fd
[2]; // parent's, child's
40 int prefork(std::string
&err
) {
42 int r
= ::socketpair(AF_UNIX
, SOCK_STREAM
, 0, fd
);
43 std::ostringstream oss
;
45 oss
<< "[" << getpid() << "]: unable to create socketpair: " << cpp_strerror(errno
);
55 oss
<< "[" << getpid() << "]: unable to fork: " << cpp_strerror(errno
);
67 int get_signal_fd() const {
68 return forked
? fd
[1] : 0;
79 int parent_wait(std::string
&err_msg
) {
83 std::ostringstream oss
;
84 int err
= safe_read_exact(fd
[0], &r
, sizeof(r
));
85 if (err
== 0 && r
== -1) {
92 oss
<< "[" << getpid() << "]: " << cpp_strerror(err
);
94 // wait for child to exit
96 err
= waitpid(childpid
, &status
, 0);
98 oss
<< "[" << getpid() << "]" << " waitpid error: " << cpp_strerror(err
);
99 } else if (WIFSIGNALED(status
)) {
100 oss
<< "[" << getpid() << "]" << " exited with a signal";
101 } else if (!WIFEXITED(status
)) {
102 oss
<< "[" << getpid() << "]" << " did not exit normally";
104 err
= WEXITSTATUS(status
);
106 oss
<< "[" << getpid() << "]" << " returned exit_status " << cpp_strerror(err
);
113 int signal_exit(int r
) {
115 // tell parent. this shouldn't fail, but if it does, pass the
116 // error back to the parent.
117 int ret
= safe_write(fd
[1], &r
, sizeof(r
));
132 int r2
= ::write(fd
[1], &r
, sizeof(r
));
133 r
+= r2
; // make the compiler shut up about the unused return code from ::write(2).