#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();
}