OpenVAS Libraries  9.0.3
pidfile.c
Go to the documentation of this file.
1 /* openvas-libraries/base
2  * $Id$
3  * Description: PID-file management.
4  *
5  * Authors:
6  * Jan-Oliver Wagner <jan-oliver.wagner@greenbone.net>
7  *
8  * Copyright:
9  * Copyright (C) 2009 Greenbone Networks GmbH
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25 
31 #include <glib.h>
32 #include <glib/gstdio.h> /* for g_fopen */
33 
34 #include <stdio.h> /* for FILE */
35 #include <stdlib.h>
36 #include <string.h> /* for strerror */
37 #include <errno.h> /* for errno */
38 #include <unistd.h> /* for getpid */
39 
40 #include "pidfile.h"
41 
45 #undef G_LOG_DOMAIN
46 #define G_LOG_DOMAIN "base pidfile"
47 
58 int
59 pidfile_create (gchar * daemon_name)
60 {
61  gchar *name_pid = g_strconcat (daemon_name, ".pid", NULL);
62  gchar *pidfile_name = g_build_filename (OPENVAS_PID_DIR, name_pid, NULL);
63  FILE *pidfile = g_fopen (pidfile_name, "w");
64 
65  g_free (name_pid);
66 
67  if (pidfile == NULL)
68  {
69  g_critical ("%s: failed to open pidfile: %s\n", __FUNCTION__,
70  strerror (errno));
71  return 1;
72  }
73  else
74  {
75  g_fprintf (pidfile, "%d\n", getpid ());
76  fclose (pidfile);
77  g_free (pidfile_name);
78  }
79  return 0;
80 }
81 
87 void
88 pidfile_remove (gchar * daemon_name)
89 {
90  gchar *name_pid = g_strconcat (daemon_name, ".pid", NULL);
91  gchar *pidfile_name = g_build_filename (OPENVAS_PID_DIR, name_pid, NULL);
92  gchar *pidfile_contents;
93 
94  g_free (name_pid);
95 
96  if (g_file_get_contents (pidfile_name, &pidfile_contents, NULL, NULL))
97  {
98  int pid = atoi (pidfile_contents);
99 
100  if (pid == getpid ())
101  {
102  g_unlink (pidfile_name);
103  }
104  g_free (pidfile_contents);
105  }
106 
107  g_free (pidfile_name);
108 }
void pidfile_remove(gchar *daemon_name)
Remove PID file.
Definition: pidfile.c:88
int pidfile_create(gchar *daemon_name)
Create a PID-file.
Definition: pidfile.c:59