Greenbone Vulnerability Management Libraries 22.30.0
pidfile.c
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2009-2023 Greenbone AG
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 */
5
10
11#include "pidfile.h"
12
13#include <errno.h> /* for errno */
14#include <glib.h> /* for g_free, gchar */
15#include <glib/gstdio.h> /* for g_unlink, g_fopen */
16#include <libgen.h> /* for libgen */
17#include <stdio.h> /* for fclose, FILE */
18#include <stdlib.h> /* for atoi */
19#include <string.h> /* for strerror */
20#include <unistd.h> /* for getpid */
21
22#undef G_LOG_DOMAIN
26#define G_LOG_DOMAIN "libgvm base"
27
39int
40pidfile_create (gchar *pid_file_path)
41{
42 FILE *pidfile;
43 gchar *copy, *dir;
44
45 if (pid_file_path == NULL)
46 return -1;
47
48 copy = g_strdup (pid_file_path);
49 dir = dirname (copy);
50
51 /* Ensure directory exists. */
52
53 if (g_mkdir_with_parents (dir, 0755)) /* "rwxr-xr-x" */
54 {
55 g_free (copy);
56 g_warning ("Failed to create PID file directory %s: %s", dir,
57 strerror (errno));
58 return 1;
59 }
60 g_free (copy);
61
62 /* Create file. */
63
64 pidfile = g_fopen (pid_file_path, "w");
65
66 if (pidfile == NULL)
67 {
68 g_critical ("%s: failed to open pidfile %s: %s\n", __func__,
69 pid_file_path, strerror (errno));
70 return 1;
71 }
72 else
73 {
74 g_fprintf (pidfile, "%d\n", getpid ());
75 fclose (pidfile);
76 }
77 return 0;
78}
79
86void
87pidfile_remove (gchar *pid_file_path)
88{
89 gchar *pidfile_contents;
90
91 if (g_file_get_contents (pid_file_path, &pidfile_contents, NULL, NULL))
92 {
93 int pid = atoi (pidfile_contents);
94
95 if (pid == getpid ())
96 {
97 g_unlink (pid_file_path);
98 }
99 g_free (pidfile_contents);
100 }
101}
int pidfile_create(gchar *pid_file_path)
Create a PID-file.
Definition pidfile.c:40
void pidfile_remove(gchar *pid_file_path)
Remove PID file.
Definition pidfile.c:87
PID-file management.