rasd: Daemonize the process

The process is put in the background and is detached from the
TTYs. The process working dir is set to '/'.
stdin, stdout and stderr are closed and cannot be used anymore.

Note: the config file 'rasd.cfg' is expected in the working
dir.

Boris:
 - simplify error paths
 - cleanup excessive comments

Signed-off-by: Jean Pihet <jean.pihet@linaro.org>
Link: http://lkml.kernel.org/r/1412933690-25576-12-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 dd95440..6734f53 100644
--- a/src/rasd.c
+++ b/src/rasd.c
@@ -161,6 +161,50 @@
 	return nr_samples;
 }
 
+/* Run as a daemon: fork off the parent, detach from TTY etc. */
+static void daemonize(void)
+{
+	pid_t pid;
+
+	pid = fork();
+	if (pid < 0)
+		exit(EXIT_FAILURE);
+	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);
+	}
+
+	/*
+	 * Catch, ignore and handle signals, ignore for now
+	 */
+	signal(SIGCHLD, SIG_IGN);
+	signal(SIGHUP, SIG_IGN);
+
+	/* Fork off for the second time to get rid of the TTY sessions */
+	pid = fork();
+	if (pid < 0)
+		exit(EXIT_FAILURE);
+	else if (pid > 0)
+		exit(EXIT_SUCCESS);
+
+	/* Set new file permissions */
+	umask(0);
+
+	/* Change the working directory to the root directory */
+	if (!chdir("/"))
+		exit(EXIT_FAILURE);
+
+	/* Close the standard file descriptors */
+	close(STDIN_FILENO);
+	close(STDOUT_FILENO);
+	close(STDERR_FILENO);
+}
+
 int main()
 {
 	struct perf_evsel *c;
@@ -168,6 +212,8 @@
 	struct cpu_map *cpus;
 	int i;
 
+	daemonize();
+
 	page_size = sysconf(_SC_PAGE_SIZE);
 
 	if (!debugfs_mount(NULL))