LIPH's C++ Codes
process.h
Go to the documentation of this file.
1#ifndef LIPH_PROCESS_H_
2#define LIPH_PROCESS_H_
3
4#include <sys/file.h>
5
6#include <cstdio>
7#include <cstdlib>
8#include <cstring>
9#include <iostream>
10#include <string>
11
12#include "liph/format.h"
13#include "liph/macros.h"
14
15namespace liph {
16
17inline void err_exit(const char *str = nullptr) {
18 if (str) perror(str);
19
20 exit(EXIT_FAILURE);
21}
22
23inline void err_exit(const std::string& str) { err_exit(str.c_str()); }
24
25inline void err_exit_if(bool error) {
26 if (error) exit(EXIT_FAILURE);
27}
28
29inline void bzero(void *p, size_t n) { memset(p, 0, n); }
30
31// Bit-mask values for 'flags' argument of become_daemon()
32#define BD_NO_CHDIR 1 // Don't chdir("/")
33#define BD_NO_CLOSE_FILES 2 // Don't close all open files
34#define BD_NO_REOPEN_STD_FDS 4 // Don't reopen stdin, stdout, and stderr to /dev/null
35#define BD_NO_UMASK0 8 // Don't do a umask(0)
36#define BD_MAX_CLOSE 8192 // Maximum file descriptors to close if sysconf(_SC_OPEN_MAX) is indeterminate
37// Become background process, returns 0 on success, -1 on error
39
40bool single_proc(const char *lock_file_path, bool exit) {
41 bool fail = !lock_file_path;
42 if (lock_file_path) {
43 int fd = open(lock_file_path, O_RDWR | O_CREAT, 0664);
44 if (fd == -1) {
45 fail = true;
46 std::cerr << format("open {} fail: {}\n", lock_file_path, std::strerror(errno));
47 } else if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
48 fail = true;
49 std::cerr << "another proc lock the file\n";
50 } else {
51 return true;
52 }
53 }
54 if (fail && exit) ::exit(EXIT_FAILURE);
55 return false;
56}
57
58} // namespace liph
59
60#endif // LIPH_PROCESS_H_
Definition: flags.h:13
Definition: algorithm.h:10
void err_exit(const char *str=nullptr)
Definition: process.h:17
bool single_proc(const char *lock_file_path, bool exit)
Definition: process.h:40
int become_daemon(int flags)
void bzero(void *p, size_t n)
Definition: process.h:29
void err_exit_if(bool error)
Definition: process.h:25