libite
2.6.1
src
pidfilefn.c
Go to the documentation of this file.
1
/* Functions for dealing with PID files (client side)
2
*
3
* Copyright (c) 2009-2021 Joachim Wiberg <troglobit@gmail.com>
4
*
5
* Permission to use, copy, modify, and/or distribute this software for any
6
* purpose with or without fee is hereby granted, provided that the above
7
* copyright notice and this permission notice appear in all copies.
8
*
9
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
*/
17
24
25
#include <errno.h>
26
#include <stdio.h>
27
#include <stdlib.h>
28
#include <signal.h>
29
#include <unistd.h>
30
31
extern
char
*
chomp
(
char
*str);
32
49
pid_t
pidfile_read
(
const
char
*
pidfile
)
50
{
51
int
pid = 0;
52
char
buf[16];
53
FILE *fp;
54
55
if
(!
pidfile
) {
56
errno = EINVAL;
57
return
-1;
58
}
59
60
fp = fopen(
pidfile
,
"r"
);
61
if
(!fp)
62
return
-1;
63
64
if
(fgets(buf,
sizeof
(buf), fp)) {
65
char
*ptr =
chomp
(buf);
66
67
if
(ptr) {
68
errno = 0;
69
pid = strtoul(ptr, NULL, 0);
70
if
(errno)
71
pid = 0;
/* Failed conversion. */
72
}
73
}
74
fclose(fp);
75
76
return
pid;
77
}
78
89
pid_t
pidfile_poll
(
const
char
*
pidfile
)
90
{
91
pid_t pid = 0;
92
int
tries = 0;
93
94
/* Timeout = 100 * 50ms = 5s */
95
while
((pid =
pidfile_read
(
pidfile
)) <= 0 && tries++ < 100)
96
usleep(50000);
/* Wait 50ms between retries */
97
98
if
(pid < 0)
99
pid = 0;
100
101
return
pid;
102
}
103
114
int
pidfile_signal
(
const
char
*
pidfile
,
int
signal)
115
{
116
int
pid = -1, ret = -1;
117
118
pid =
pidfile_read
(
pidfile
);
119
if
(pid <= 0)
120
return
1;
121
122
ret = kill(pid, signal);
123
if
(!ret && signal == SIGKILL)
124
ret = remove(
pidfile
);
125
126
return
ret;
127
}
128
pidfile
FILE int pidfile(const char *basename)
Definition
pidfile.c:71
pidfile_poll
pid_t pidfile_poll(const char *pidfile)
Definition
pidfilefn.c:89
pidfile_signal
int pidfile_signal(const char *pidfile, int signal)
Definition
pidfilefn.c:114
pidfile_read
pid_t pidfile_read(const char *pidfile)
Definition
pidfilefn.c:49
chomp
char * chomp(char *str)
Definition
chomp.c:38
Generated by
1.13.2