Line data Source code
1 : #include <fcntl.h> 2 : #include <signal.h> 3 : #include <errno.h> 4 : 5 : #include "monitor.hpp" 6 : #include "util.hpp" 7 : #include "log.hpp" 8 : 9 : 10 29 : Monitor::Monitor(std::string& fifoname) 11 : { 12 29 : if (fifoname == ""){ 13 29 : m_fifo_fd = -1; 14 29 : return; 15 : } 16 0 : else if (!is_fifo(fifoname.c_str())) 17 : { 18 0 : LOG_ERR("%s does not exist or is not a FIFO. Monitor disabled.", fifoname.c_str()); 19 : return; 20 : } 21 : 22 0 : signal(SIGPIPE, SIG_IGN); 23 : 24 : // Opening a FIFO for write-only will fail if there is no reader, so we fake a reader 25 0 : int tmpfd = open(fifoname.c_str(), O_RDONLY | O_NDELAY); 26 : 27 0 : m_fifo_fd = open(fifoname.c_str(), O_WRONLY | O_NDELAY | O_NONBLOCK); 28 0 : if (m_fifo_fd < 0) 29 : { 30 0 : LOG_ERR("Cannot open monitoring FIFO %s, error %d: %s", fifoname.c_str(), errno, strerror(errno)); 31 : } 32 0 : LOG_INFO("Monitoring FIFO %s opened, fd=%d", fifoname.c_str(), m_fifo_fd); 33 0 : fcntl(m_fifo_fd, F_SETPIPE_SZ, 1048576); 34 0 : close(tmpfd); 35 0 : } 36 : 37 : 38 29 : Monitor::~Monitor() 39 : { 40 29 : close(m_fifo_fd); 41 29 : } 42 : 43 : 44 0 : bool Monitor::is_fifo(const char *filename) 45 : { 46 0 : struct stat stat_p; 47 0 : if (0 != stat(filename, &stat_p)) 48 : { 49 : // does not exist 50 : return false; 51 : } 52 0 : if (!S_ISFIFO(stat_p.st_mode)) 53 : { 54 : // not a fifo 55 0 : return false; 56 : } 57 : return true; 58 : } 59 : 60 : 61 6 : std::string Monitor::get_serialized_message() 62 : { 63 6 : return m_message.dump(); 64 : } 65 : 66 : 67 735 : void Monitor::write_message() 68 : { 69 735 : if(m_fifo_fd == -1){ 70 735 : return; 71 : } 72 0 : std::string msg = get_serialized_message()+"\n"; 73 0 : const char* msg_ptr = msg.c_str(); 74 0 : size_t bytes_written = 0; 75 : 76 0 : while (bytes_written < msg.size()) { 77 0 : ssize_t result = write(m_fifo_fd, msg_ptr + bytes_written, msg.size() - bytes_written); 78 0 : if (result == -1) { 79 0 : if (errno == EINTR) { 80 0 : continue; 81 : } 82 0 : else if (errno == EPIPE) { 83 : break; 84 : } 85 0 : LOG_WARN("Error writing to FIFO. Code %d: %s ", errno, strerror(errno)); 86 : break; 87 : } 88 0 : bytes_written += result; 89 : } 90 0 : }