--- a/syslog_kernel.c Tue May 30 12:05:42 2006 +0200
+++ b/syslog_kernel.c Tue May 30 12:34:25 2006 +0200
@@ -188,10 +188,109 @@
program_handler(SIGHUP, reconfig_handler);
}
+static void check_pid()
+{
+ int fh;
+ char name[MAX_STRING];
+ char buffer[MAX_STRING];
+ int buffer_size;
+ int pid, res;
+
+ assert (get_config(PID_FILE, name, MAX_STRING) > 0);
+
+ fh = open(name, O_RDONLY);
+ if (fh == -1)
+ {
+ /* If the file doesn't exist, it's normal. */
+ return;
+ }
+
+ buffer_size = MAX_STRING;
+ buffer_size = read(fh, buffer, buffer_size);
+ if (buffer_size <= 0)
+ {
+ fprintf(stderr, "Error reading the pid file: %s\n",
+ strerror(errno));
+ close(fh);
+ return;
+ }
+ buffer[buffer_size] = '\0';
+
+ pid = atoi(buffer);
+
+ if (pid > 0)
+ {
+ res = kill(pid, SIGHUP);
+ if (res == 0)
+ {
+ /* The syslog_kernel seems to be running and restared */
+ fprintf(stderr,"syslog_kernel running. Restarted.\n");
+ close(fh);
+ exit(0);
+ } else if (res == -1)
+ {
+ fprintf(stderr,"An old pid file has been found. "
+ "Ignoring it.\n");
+ }
+ }
+
+ close(fh);
+}
+
+static void write_pid()
+{
+ int fh;
+ char name[MAX_STRING];
+ char buffer[MAX_STRING];
+ int buffer_size;
+ int res;
+
+ assert (get_config(PID_FILE, name, MAX_STRING) > 0);
+
+ fh = open(name, O_WRONLY | O_TRUNC | O_CREAT, 0644);
+ if (fh == -1)
+ {
+ fprintf(stderr, "Error opening the pid file for write: %s\n",
+ strerror(errno));
+ return;
+ }
+
+ buffer_size = snprintf(buffer, MAX_STRING, "%i", getpid());
+ if (buffer_size < MAX_STRING)
+ {
+ buffer[buffer_size++] = '\n';
+ }
+
+ res = write(fh, buffer, buffer_size);
+ if (buffer_size <= 0)
+ fprintf(stderr, "Error writting the pid file: %s\n",
+ strerror(errno));
+
+ close(fh);
+}
+
+static void remove_pid()
+{
+ int res;
+ char name[MAX_STRING];
+
+ assert (get_config(PID_FILE, name, MAX_STRING) > 0);
+ res = unlink(name);
+
+ if (res == -1)
+ fprintf(stderr, "Error unlinking the pid file: %s\n",
+ strerror(errno));
+}
+
+
+
int main(int argn, char *argv[])
{
int res;
+ check_pid();
+ write_pid();
+
install_signal_handlers();
do
@@ -228,4 +327,6 @@
wait_childs_die();
}
while(reconfig == true);
+
+ remove_pid();
}