diff options
-rw-r--r-- | daemon.c | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/daemon.c b/daemon.c new file mode 100644 index 0000000..6bdb46b --- /dev/null +++ b/daemon.c @@ -0,0 +1,80 @@ +#include <stdio.h> +#include <unistd.h> +#include <fcntl.h> +#include <signal.h> +#include <time.h> +#include <stdlib.h> +#include <syslog.h> + +volatile sig_atomic_t get_info = 0; +volatile sig_atomic_t signal_counter = 0; + +void handler(int s) +{ + signal(SIGUSR1, handler); + signal(SIGALRM, handler); + + switch(s) { + case SIGUSR1: + get_info = 1; + ++signal_counter; + break; + case SIGALRM: + get_info = 1; + alarm(300); + } +} + +int main() +{ + int fd, pid; + char *path = "/tmp/ordinary_daemon.log"; + FILE *file; + time_t start, end; + double dif; + + signal(SIGUSR1, handler); + signal(SIGALRM, handler); + close(0); + close(1); + close(2); + open("/dev/null", O_RDONLY); + open("/dev/null", O_WRONLY); + open("/dev/null", O_WRONLY); + chdir("/"); + pid = fork(); + if(pid > 0) + exit(0); + setsid(); + pid = fork(); + if(pid > 0) + exit(0); + fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666); + file = fdopen(fd, "w"); + if(fd == -1) { + perror("can't open file"); + exit(1); + } + openlog("ordinary daemon", 0, LOG_USER); + syslog(LOG_INFO, "daemon started"); + alarm(300); + pid = getpid(); + time(&start); + + while(1) { + pause(); + if(get_info) { + time(&end); + dif = difftime(end, start); + fprintf(file, "time spent (in sec): %.2f pid: %u SIGUSR1: %u\n", + dif, pid, signal_counter); + syslog(LOG_INFO, "time spent (in sec): %.2f pid: %u SIGUSR1: %u", + dif, pid, signal_counter); + fflush(file); + get_info = 0; + } + } + closelog(); + close(fd); + return 0; +} |