+static int is_already_running(const char *pidfile)
+{
+ struct stat s;
+ char pidstr[16], procpath[256] = { 0 };
+ int fd, ret, pid;
+
+ fd = open(pidfile, O_RDONLY);
+ if (fd < 0) {
+ /* No pid, no running instance */
+ return 0;
+ }
+
+ ret = read(fd, pidstr, sizeof(pidstr) - 1);
+ if (ret < 0) {
+ pr_err("Failed to read pid file: %m\n");
+ close(fd);
+
+ return ret;
+ }
+ close(fd);
+
+ pidstr[ret] = 0;
+
+ ret = sscanf(pidstr, "%d", &pid);
+
+ /* Corrupted pid data? Maybe leftover from prev boot or something */
+ if (ret != 1)
+ return 0;
+
+ snprintf(procpath, sizeof(procpath) - 1, "/proc/%d/", pid);
+
+ ret = stat(procpath, &s);
+
+ if (ret < 0) {
+ pr_info("Ignoring stale pid %d from pid file %s\n",
+ pid, pidfile);
+
+ return 0;
+ }
+
+ pr_err("Process %d is already running as stated in pid file %s\n",
+ pid, pidfile);
+
+ return 1;
+}
+
+static int write_pidfile(const char *pidfile)
+{
+ char pidstr[16];
+ int fd, ret;
+
+ fd = open(pidfile, O_WRONLY | O_CREAT, 0644);
+ if (fd < 0) {
+ pr_err("Failed to open pidfile %s for writing: %m\n", pidfile);
+ return -1;
+ }
+
+ ret = snprintf(pidstr, sizeof(pidstr), "%d", getpid());
+ ret = write(fd, pidstr, ret);
+ if (ret < 0)
+ pr_err("Failed to write to pidfile %s: %m\n", pidfile);
+
+ close(fd);
+
+ return ret;
+}
+