72 lines
1.1 KiB
C
72 lines
1.1 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
#include <sys/types.h>
|
||
|
#include <sys/stat.h>
|
||
|
#include <fcntl.h>
|
||
|
#include <errno.h>
|
||
|
#include <signal.h>
|
||
|
|
||
|
int pidfile_create(const char *filename)
|
||
|
{
|
||
|
int fd = open(filename, O_CREAT | O_EXCL | O_RDWR, 0644);
|
||
|
if (fd < 0)
|
||
|
return -1;
|
||
|
|
||
|
char buf[8];
|
||
|
int len = snprintf(buf, sizeof(buf), "%d", getpid());
|
||
|
write(fd, buf, len);
|
||
|
|
||
|
close(fd);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int pidfile_remove(const char *filename)
|
||
|
{
|
||
|
return unlink(filename);
|
||
|
}
|
||
|
|
||
|
pid_t pidfile_check(const char *filename, int remove_stale)
|
||
|
{
|
||
|
int fd = open(filename, O_RDWR);
|
||
|
if (fd < 0) {
|
||
|
if (errno == ENOENT) {
|
||
|
errno = 0;
|
||
|
return 0;
|
||
|
}
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
char buf[9];
|
||
|
int len = read(fd, buf, sizeof(buf) -1);
|
||
|
buf[len] = '\0';
|
||
|
|
||
|
close(fd);
|
||
|
|
||
|
char *tmp;
|
||
|
pid_t pid = strtol(buf, &tmp, 10);
|
||
|
if (len == 0 || tmp == buf)
|
||
|
pid = -1;
|
||
|
|
||
|
/* just return the pid */
|
||
|
if (!remove_stale)
|
||
|
return pid;
|
||
|
|
||
|
/* invalid pid, remove stale file */
|
||
|
if (pid == -1) {
|
||
|
pidfile_remove(filename);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
/* check if pid is still running */
|
||
|
if (kill(pid, 0) == 0 || errno != ESRCH) {
|
||
|
errno = 0;
|
||
|
return pid;
|
||
|
}
|
||
|
|
||
|
errno = 0;
|
||
|
pidfile_remove(filename);
|
||
|
return 0;
|
||
|
}
|