#include <string.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <fcntl.h>
static void run_kmsg_dump_daemon(void)
{
int pid;
pid = fork();
if (pid == 0) {
int fd_1;
int fd_2;
int i;
/* start */
if (fork() != 0)
exit(0);
if (setsid() < 0)
perror("setsid");
if (fork() != 0)
exit(0);
chdir("/");
umask(0);
for (i = 0; i < 64; i++)
close(i);
/* done */
fd_1 = open("/proc/kmsg", O_RDONLY);
if (fd_1 < 0) {
fprintf(stdout, "open error: %s\n", strerror(errno));
goto out;
}
/*
determine the name of new log file
*/
for (i = 0; i < 1000; i++) {
char log_file[1024] = { '\0' };
(void) snprintf(log_file, sizeof(log_file) - 1, "%s_%d.log", "/data/kmsg", i);
fd_2 = open(log_file, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
if (fd_2 > 0)
break;
}
while (1) {
struct timeval time;
fd_set rfd;
int nready;
FD_ZERO(&rfd);
FD_SET(fd_1, &rfd);
time.tv_sec = 1;
time.tv_usec = 0;
nready = select(FD_SETSIZE, &rfd, NULL, NULL, &time);
if (nready > 0) {
char buf[4096] = {'\0'};
int n;
n = read(fd_1, buf, sizeof(buf) - 1);
if (n > 0)
(void) write(fd_2, buf, n);
} else if (nready < 0) {
fprintf(stdout, "'select()' failed with error: %s\n", strerror(errno));
break;
}
}
out:
exit(0)
}
/* let parent continue its job */
return;
}
int main()
{
run_kmsg_dump_daemon();
}
本文介绍了一个用于捕获内核消息并将其记录到文件中的守护进程的实现方法。该守护进程通过fork三次确保后台运行,并设置会话ID以避免控制终端的影响。通过打开/proc/kmsg读取内核消息,使用select监听读事件,当有新的内核消息时写入到日志文件中。

5661

被折叠的 条评论
为什么被折叠?



