64 lines
1.6 KiB
C++
64 lines
1.6 KiB
C++
#include <time.h>
|
|
#include <ctime>
|
|
#include <iostream>
|
|
#include <fstream>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/types.h>
|
|
#include <cstring>
|
|
#include <csignal>
|
|
|
|
const char* LOG_FIFO_NAME = "/pipe/log";
|
|
|
|
std::string LOG_DIR = "/log_data";
|
|
|
|
int pipeFd;
|
|
|
|
void handle_signal(int sig) {
|
|
if (sig == SIGTERM || sig == SIGINT) {
|
|
close(pipeFd);
|
|
unlink(LOG_FIFO_NAME);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
signal(SIGINT, handle_signal);
|
|
signal(SIGTERM, handle_signal);
|
|
mkdir(LOG_DIR.c_str(), 0755);
|
|
|
|
// Create or open the named pipe
|
|
mkfifo(LOG_FIFO_NAME, 0666);
|
|
|
|
// Open the pipe for reading
|
|
pipeFd = open(LOG_FIFO_NAME, O_RDONLY);
|
|
if (pipeFd == -1) {
|
|
std::cout << "Error opening pipe!" << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
// Read log messages from the pipe and write them to the log file
|
|
char buffer[256];
|
|
while (true) {
|
|
ssize_t bytesRead = read(pipeFd, buffer, sizeof(buffer) - 1);
|
|
if (bytesRead > 0) {
|
|
buffer[bytesRead] = '\0';
|
|
time_t now = time(0);
|
|
struct tm tstruct;
|
|
tstruct = *localtime(&now);
|
|
char filename[12];
|
|
std::strftime(filename, 12, "%Y-%m-%d", &tstruct);
|
|
std::ofstream log_file;
|
|
log_file.open(LOG_DIR + "/" + filename + ".log", std::ios_base::app);
|
|
char timestamp[32];
|
|
std::strftime(timestamp, 32, "%Y/%m/%d %H:%M:%S ", &tstruct);
|
|
log_file << timestamp << buffer << std::endl;
|
|
log_file.close();
|
|
}
|
|
}
|
|
|
|
// Clean up
|
|
close(pipeFd);
|
|
|
|
return 0;
|
|
} |