Greenbone Vulnerability Management Libraries  11.0.1
pidfile.c
Go to the documentation of this file.
1 /* Copyright (C) 2009-2019 Greenbone Networks GmbH
2  *
3  * SPDX-License-Identifier: GPL-2.0-or-later
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
25 #include "pidfile.h"
26 
27 #include <errno.h> /* for errno */
28 #include <glib.h> /* for g_free, gchar, g_build_filename, g_strconcat */
29 #include <glib/gstdio.h> /* for g_unlink, g_fopen */
30 #include <stdio.h> /* for fclose, FILE */
31 #include <stdlib.h> /* for atoi */
32 #include <string.h> /* for strerror */
33 #include <unistd.h> /* for getpid */
34 
38 #undef G_LOG_DOMAIN
39 #define G_LOG_DOMAIN "base pidfile"
40 
51 int
52 pidfile_create (gchar *daemon_name)
53 {
54  gchar *name_pid = g_strconcat (daemon_name, ".pid", NULL);
55  gchar *pidfile_name = g_build_filename (GVM_PID_DIR, name_pid, NULL);
56  FILE *pidfile = g_fopen (pidfile_name, "w");
57 
58  g_free (name_pid);
59 
60  if (pidfile == NULL)
61  {
62  g_critical ("%s: failed to open pidfile: %s\n", __FUNCTION__,
63  strerror (errno));
64  return 1;
65  }
66  else
67  {
68  g_fprintf (pidfile, "%d\n", getpid ());
69  fclose (pidfile);
70  g_free (pidfile_name);
71  }
72  return 0;
73 }
74 
80 void
81 pidfile_remove (gchar *daemon_name)
82 {
83  gchar *name_pid = g_strconcat (daemon_name, ".pid", NULL);
84  gchar *pidfile_name = g_build_filename (GVM_PID_DIR, name_pid, NULL);
85  gchar *pidfile_contents;
86 
87  g_free (name_pid);
88 
89  if (g_file_get_contents (pidfile_name, &pidfile_contents, NULL, NULL))
90  {
91  int pid = atoi (pidfile_contents);
92 
93  if (pid == getpid ())
94  {
95  g_unlink (pidfile_name);
96  }
97  g_free (pidfile_contents);
98  }
99 
100  g_free (pidfile_name);
101 }
pidfile_remove
void pidfile_remove(gchar *daemon_name)
Remove PID file.
Definition: pidfile.c:81
pidfile.h
PID-file management.
pidfile_create
int pidfile_create(gchar *daemon_name)
Create a PID-file.
Definition: pidfile.c:52