rasd: Log debug info and events data to files

The log file is '/var/log/rasd.log'; the data file
is '/var/log/rasd.data'.

Note: all debug and informational messages go to the log
file; stderr is not used anymore.

Boris:
 - s/open_output_files/open_log_files/g
 - cleanup in the error case in open_log_files
 - move success message to the end of daemonize(),
   after we've passed all checks

Signed-off-by: Jean Pihet <jean.pihet@linaro.org>
Link: http://lkml.kernel.org/r/1412933690-25576-13-git-send-email-jean.pihet@linaro.org
Signed-off-by: Borislav Petkov <bp@suse.de>
diff --git a/src/rasd.c b/src/rasd.c
index 6734f53..d87311a 100644
--- a/src/rasd.c
+++ b/src/rasd.c
@@ -11,10 +11,13 @@
 #define EVENT_STR_MAX_LENGTH	1024
 #define SYS_NAME_SEPARATOR	":"
 #define RASD_CFG_FILE		"rasd.cfg"
+#define RASD_LOG_FILE		"/var/log/rasd.log"
+#define RASD_DATA_FILE		"/var/log/rasd.data"
 
 unsigned int page_size;
 struct perf_evlist *evlist;
 struct perf_rasd rasd;
+FILE *log_file, *data_file;
 
 /* Check if the read line is a valid config file line.*/
 static bool cfg_valid_line(char *str)
@@ -161,23 +164,44 @@
 	return nr_samples;
 }
 
+static int open_log_files(void)
+{
+	log_file = fopen(RASD_LOG_FILE, "a");
+	if (!log_file) {
+		fprintf(stderr, "Cannot open log file " RASD_LOG_FILE " for writing\n");
+		exit(EXIT_FAILURE);
+	}
+
+	data_file = fopen(RASD_DATA_FILE, "a");
+	if (!data_file) {
+		err("Cannot open data file " RASD_DATA_FILE " for writing");
+		goto err;
+	}
+	return 0;
+
+err:
+	fclose(log_file);
+	return -1;
+}
+
 /* Run as a daemon: fork off the parent, detach from TTY etc. */
 static void daemonize(void)
 {
 	pid_t pid;
 
+	if (open_log_files())
+		exit(EXIT_FAILURE);
+
 	pid = fork();
 	if (pid < 0)
-		exit(EXIT_FAILURE);
+		err("1st fork()");
 	else if (pid > 0)
 		/* Let the parent terminate */
 		exit(EXIT_SUCCESS);
 
 	/* The child process becomes session leader */
-	if (setsid() < 0) {
-		perror("setsid()");
-		exit(EXIT_FAILURE);
-	}
+	if (setsid() < 0)
+		err("setsid()");
 
 	/*
 	 * Catch, ignore and handle signals, ignore for now
@@ -188,7 +212,7 @@
 	/* Fork off for the second time to get rid of the TTY sessions */
 	pid = fork();
 	if (pid < 0)
-		exit(EXIT_FAILURE);
+		err("2nd fork()");
 	else if (pid > 0)
 		exit(EXIT_SUCCESS);
 
@@ -197,7 +221,9 @@
 
 	/* Change the working directory to the root directory */
 	if (!chdir("/"))
-		exit(EXIT_FAILURE);
+		err("Cannot chdir");
+
+	fprintf(log_file, "\n*** rasd starting ***\n");
 
 	/* Close the standard file descriptors */
 	close(STDIN_FILENO);