PidFile.hxx 2.25 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifndef MPD_PID_FILE_HXX
#define MPD_PID_FILE_HXX

#include "fs/FileSystem.hxx"
#include "fs/AllocatedPath.hxx"
25
#include "system/Error.hxx"
26

27 28
#include <cassert>

29
#include <string.h>
30
#include <unistd.h>
31
#include <stdlib.h>
32
#include <fcntl.h>
33 34

class PidFile {
35
	int fd;
36 37

public:
38
	PidFile(const AllocatedPath &path):fd(-1) {
39 40 41
		if (path.IsNull())
			return;

42
		fd = OpenFile(path, O_WRONLY|O_CREAT|O_TRUNC, 0666).Steal();
43
		if (fd < 0) {
44
			const std::string utf8 = path.ToUTF8();
45 46
			throw FormatErrno("Failed to create pid file \"%s\"",
					  utf8.c_str());
47 48 49 50 51
		}
	}

	PidFile(const PidFile &) = delete;

52
	void Close() noexcept {
53
		if (fd < 0)
54 55
			return;

56
		close(fd);
57 58
	}

59
	void Delete(const AllocatedPath &path) noexcept {
60
		if (fd < 0) {
61 62 63 64 65 66
			assert(path.IsNull());
			return;
		}

		assert(!path.IsNull());

67
		close(fd);
68
		unlink(path.c_str());
69 70
	}

71
	void Write(pid_t pid) noexcept {
72
		if (fd < 0)
73 74
			return;

75 76
		char buffer[64];
		sprintf(buffer, "%lu\n", (unsigned long)pid);
77 78

		write(fd, buffer, strlen(buffer));
79
		close(fd);
80 81
	}

82
	void Write() noexcept {
83
		if (fd < 0)
84 85 86 87 88 89
			return;

		Write(getpid());
	}
};

90 91
gcc_pure
static inline pid_t
92
ReadPidFile(Path path) noexcept
93
{
94 95
	auto fd = OpenFile(path, O_RDONLY, 0);
	if (!fd.IsDefined())
96 97
		return -1;

98
	pid_t pid = -1;
99

100
	char buffer[32];
101
	auto nbytes = fd.Read(buffer, sizeof(buffer) - 1);
102 103 104 105 106 107 108 109 110
	if (nbytes > 0) {
		buffer[nbytes] = 0;

		char *endptr;
		auto value = strtoul(buffer, &endptr, 10);
		if (endptr > buffer)
			pid = value;
	}

111 112 113
	return pid;
}

114
#endif