Apache Mesos
exists.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_WINDOWS_EXISTS_HPP__
14 #define __STOUT_OS_WINDOWS_EXISTS_HPP__
15 
16 #include <string>
17 
18 #include <stout/error.hpp>
19 #include <stout/windows.hpp>
20 
22 
23 
24 namespace os {
25 
26 
27 inline bool exists(const std::string& path)
28 {
29  // NOTE: `GetFileAttributes` returns `INVALID_FILE_ATTRIBUTES` if the file
30  // could not be opened for any reason. Checking for one of two 'not found'
31  // error codes (`ERROR_FILE_NOT_FOUND` or `ERROR_PATH_NOT_FOUND`) is a
32  // reliable test for whether the file or directory exists. See also [1] for
33  // more information on this technique.
34  //
35  // [1] http://blogs.msdn.com/b/oldnewthing/archive/2007/10/23/5612082.aspx
36  const DWORD attributes = ::GetFileAttributesW(
37  ::internal::windows::longpath(path).data());
38 
39  if (attributes == INVALID_FILE_ATTRIBUTES) {
40  const DWORD error = ::GetLastError();
41  if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) {
42  return false;
43  }
44  }
45 
46  // Note that `ERROR_ACCESS_DENIED` etc. indicates the path does exist, but
47  // `INVALID_FILE_ATTRIBUTES` would still be returned.
48 
49  return true;
50 }
51 
52 
53 // Determine if the process identified by pid exists.
54 // NOTE: Zombie processes have a pid and therefore exist. See
55 // os::process(pid) to get details of a process.
56 inline bool exists(pid_t pid)
57 {
58  SharedHandle handle(
59  ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid),
60  ::CloseHandle);
61 
62  return handle.get_handle() != nullptr;
63 }
64 
65 
66 } // namespace os {
67 
68 #endif // __STOUT_OS_WINDOWS_EXISTS_HPP__
Definition: path.hpp:29
bool exists(const std::string &path)
Definition: exists.hpp:26
Definition: windows.hpp:72
Definition: posix_signalhandler.hpp:23
DWORD pid_t
Definition: windows.hpp:181
std::string error(const std::string &msg, uint32_t code)
std::wstring longpath(const std::string &path)
Definition: longpath.hpp:38