trace-cmd listen: Add a pid file when in daemon mode

When trace-cmd listen is started in daemon mode, create the file
/var/run/trace-cmd-net.pid that holds the pid of the daemon.

Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
diff --git a/trace-listen.c b/trace-listen.c
index 420b68d..1e3375f 100644
--- a/trace-listen.c
+++ b/trace-listen.c
@@ -37,6 +37,8 @@
 
 #define MAX_OPTION_SIZE 4096
 
+#define VAR_RUN_DIR		"/var/run"
+
 static char *default_output_dir = ".";
 static char *output_dir;
 static char *default_output_file = "trace";
@@ -50,6 +52,8 @@
 
 static int proto_ver;
 
+static int do_daemon;
+
 #define  TEMP_FILE_STR "%s.%s:%s.cpu%d", output_file, host, port, cpu
 static char *get_temp_file(const char *host, const char *port, int cpu)
 {
@@ -155,6 +159,24 @@
 	va_end(ap);
 }
 
+static void make_pid_name(int mode, char *buf)
+{
+	snprintf(buf, PATH_MAX, VAR_RUN_DIR "/trace-cmd-net.pid");
+}
+
+static void remove_pid_file(void)
+{
+	char buf[PATH_MAX];
+	int mode = do_daemon;
+
+	if (!do_daemon)
+		return;
+
+	make_pid_name(mode, buf);
+
+	unlink(buf);
+}
+
 void pdie(const char *fmt, ...)
 {
 	va_list ap;
@@ -169,6 +191,9 @@
 		fprintf(logfp, "\n%s\n", str);
 	else
 		fprintf(stderr, "\n%s\n", str);
+
+	remove_pid_file();
+
 	exit(-1);
 }
 
@@ -802,6 +827,28 @@
 	} while (!done);
 }
 
+static void make_pid_file(void)
+{
+	char buf[PATH_MAX];
+	int mode = do_daemon;
+	int fd;
+
+	if (!do_daemon)
+		return;
+
+	make_pid_name(mode, buf);
+
+	fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+	if (fd < 0) {
+		perror(buf);
+		return;
+	}
+
+	sprintf(buf, "%d\n", getpid());
+	write(fd, buf, strlen(buf));
+	close(fd);
+}
+
 static void do_listen(char *port)
 {
 	struct addrinfo hints;
@@ -811,6 +858,8 @@
 	if (!debug)
 		signal_setup(SIGCHLD, clean_up);
 
+	make_pid_file();
+
 	memset(&hints, 0, sizeof(hints));
 	hints.ai_family = AF_UNSPEC;
 	hints.ai_socktype = SOCK_STREAM;
@@ -843,10 +892,14 @@
 	do_accept_loop(sfd);
 
 	kill_clients();
+
+	remove_pid_file();
 }
 
 static void start_daemon(void)
 {
+	do_daemon = 1;
+
 	if (daemon(1, 0) < 0)
 		die("starting daemon");
 }