1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <algorithm>
#include <string>
//
// a semaphore with system scope.
//
// 1. no race conditions between Post() / GetValue() , better than flock().
// 2. when a running process be killed, automatically release all.
// 3. no file on disk, no accidently delete .
// 4. no tcp/udp socket, no confliction, no port consumption.
//
class SysSem {
public:
SysSem() : _fd(-1) { memset(&_addr, 0, sizeof(_addr)); }
~SysSem();
void Init(std::string id);
bool Post();
bool GetValue();
const char* GetID() const;
private:
struct sockaddr_un _addr;
int _fd;
};
void SysSem::Init(std::string id) {
_addr.sun_family = AF_UNIX;
const size_t len = std::min(id.size(), sizeof(_addr.sun_path) - 2); // 2 = start null and end null byte
// abstract namespace socket address , _addr.sun_path[0] is a null byte ('\0')
memcpy(_addr.sun_path + 1, id.c_str(), len);
// memcpy(_addr.sun_path + 0, id.c_str(), len);
}
const char* SysSem::GetID() const { return &_addr.sun_path[1]; }
SysSem::~SysSem() {
if (_fd >= 0) {
::close(_fd);
_fd = -1;
}
}
bool SysSem::Post() {
_fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (_fd < 0) {
return false;
}
if ((0 != ::bind(_fd, (struct sockaddr*)&_addr, sizeof(_addr))) || (0 != listen(_fd, 65536))) {
return false;
}
return true;
}
bool SysSem::GetValue() {
const int clientFD = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (clientFD < 0) {
return false;
}
const bool ret = (0 == ::connect(clientFD, (struct sockaddr*)&_addr, sizeof(_addr)));
::close(clientFD);
return ret;
}
#include <assert.h>
#include <stdio.h>
int main(int argc, char** argv) {
if (argc != 3) {
fprintf(stderr, "usage: %s abstract-path post/get\n", argv[0]);
exit(1);
}
SysSem inst;
inst.Init(argv[1]);
if (0 == strcasecmp(argv[2], "post")) {
assert(inst.Post());
SysSem check;
check.Init(argv[1]);
assert(check.GetValue());
printf("ok, i am the only one under %s. running ...\n", inst.GetID());
pause();
} else if (0 == strcasecmp(argv[2], "get")) {
assert(inst.GetValue());
printf("a process is running under %s. \n", inst.GetID());
} else {
printf("unknown cmd \n");
}
return 0;
}
|