OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "chrome/common/multi_process_lock.h" | |
6 | |
7 #include <sys/socket.h> | |
8 #include <sys/un.h> | |
9 #include <unistd.h> | |
10 | |
11 #include "base/eintr_wrapper.h" | |
12 #include "base/logging.h" | |
13 | |
14 class MultiProcessLockLinux : public MultiProcessLock { | |
15 public: | |
16 explicit MultiProcessLockLinux(const std::string& name) | |
17 : name_(name), fd_(-1) { } | |
18 | |
19 virtual ~MultiProcessLockLinux() { | |
20 if (fd_ != -1) { | |
21 Unlock(); | |
22 } | |
23 } | |
24 | |
25 virtual bool TryLock() { | |
26 if (fd_ != -1) { | |
27 DLOG(ERROR) << "MultiProcessLock is already locked - " << name_; | |
28 return true; | |
29 } | |
30 | |
31 if (name_.length() > MULTI_PROCESS_LOCK_NAME_MAX_LEN) { | |
32 LOG(ERROR) << "Socket name too long - " << name_; | |
33 return false; | |
34 } | |
35 | |
36 struct sockaddr_un address; | |
37 memset(&address, 0, sizeof(address)); | |
Mark Mentovai
2010/11/15 23:42:55
Or you could have just written
struct sockaddr
dmac
2010/11/15 23:55:24
I usually go with the memset just in case someone
| |
38 memcpy(&address.sun_path[1], name_.data(), name_.length()); | |
39 | |
40 // Must set the first character of the path to something non-zero | |
41 // before we call SUN_LEN which depends on strcpy working. | |
42 address.sun_path[0] = '@'; | |
43 size_t length = SUN_LEN(&address); | |
44 | |
45 // Reset the first character of the path back to zero so that | |
46 // bind returns an abstract name socket. | |
47 address.sun_path[0] = 0; | |
48 address.sun_family = AF_LOCAL; | |
49 | |
50 int socket_fd = socket(AF_LOCAL, SOCK_STREAM, 0); | |
51 if (socket_fd < 0) { | |
52 PLOG(ERROR) << "Couldn't create socket - " << name_; | |
53 return false; | |
54 } | |
55 | |
56 if (bind(socket_fd, | |
57 reinterpret_cast<sockaddr *>(&address), | |
58 length) == 0) { | |
59 fd_ = socket_fd; | |
60 return true; | |
61 } else { | |
62 NOTREACHED() << "Couldn't bind socket - " << address.sun_path; | |
63 HANDLE_EINTR(close(socket_fd)); | |
64 return false; | |
65 } | |
66 } | |
67 | |
68 virtual void Unlock() { | |
69 if (fd_ == -1) { | |
70 DLOG(ERROR) << "Over-unlocked MultiProcessLock - " << name_; | |
71 return; | |
72 } | |
73 HANDLE_EINTR(close(fd_)); | |
74 fd_ = -1; | |
75 } | |
76 | |
77 private: | |
78 std::string name_; | |
79 int fd_; | |
80 DISALLOW_COPY_AND_ASSIGN(MultiProcessLockLinux); | |
81 }; | |
82 | |
83 MultiProcessLock* MultiProcessLock::Create(const std::string &name) { | |
84 return new MultiProcessLockLinux(name); | |
85 } | |
OLD | NEW |