1 // Copyright (c) 2012 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.
5 #ifndef BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
6 #define BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
10 #include "base/basictypes.h"
11 #include "base/base_export.h"
12 #include "base/win/scoped_handle.h"
17 // Manages the closing of process and thread handles from PROCESS_INFORMATION
18 // structures. Allows clients to take ownership of either handle independently.
19 class BASE_EXPORT ScopedProcessInformation
{
21 // Helper object to contain the effect of Receive() to the funtion that needs
25 explicit Receiver(ScopedProcessInformation
* owner
)
28 ~Receiver() { owner_
->Set(info_
); }
30 operator PROCESS_INFORMATION
*() { return &info_
; }
33 PROCESS_INFORMATION info_
;
34 ScopedProcessInformation
* owner_
;
37 ScopedProcessInformation();
38 ~ScopedProcessInformation();
40 // Returns an object that may be passed to API calls such as CreateProcess.
41 // DCHECKs that the object is not currently holding any handles.
42 // HANDLEs stored in the returned PROCESS_INFORMATION will be owned by this
44 // The intended use case is something like this:
45 // if (::CreateProcess(..., startup_info, scoped_proces_info.Receive()))
48 // Returns true iff this instance is holding a thread and/or process handle.
51 // Closes the held thread and process handles, if any.
54 // Populates this instance with the provided |process_info|.
55 void Set(const PROCESS_INFORMATION
& process_info
);
57 // Populates this instance with duplicate handles and the thread/process IDs
58 // from |other|. Returns false in case of failure, in which case this instance
59 // will be completely unpopulated.
60 bool DuplicateFrom(const ScopedProcessInformation
& other
);
62 // Transfers ownership of the held PROCESS_INFORMATION, if any, away from this
64 PROCESS_INFORMATION
Take();
66 // Transfers ownership of the held process handle, if any, away from this
67 // instance. Note that the related process_id will also be cleared.
68 HANDLE
TakeProcessHandle();
70 // Transfers ownership of the held thread handle, if any, away from this
71 // instance. Note that the related thread_id will also be cleared.
72 HANDLE
TakeThreadHandle();
74 // Returns the held process handle, if any, while retaining ownership.
75 HANDLE
process_handle() const {
76 return process_handle_
.Get();
79 // Returns the held thread handle, if any, while retaining ownership.
80 HANDLE
thread_handle() const {
81 return thread_handle_
.Get();
84 // Returns the held process id, if any.
85 DWORD
process_id() const {
89 // Returns the held thread id, if any.
90 DWORD
thread_id() const {
95 ScopedHandle process_handle_
;
96 ScopedHandle thread_handle_
;
100 DISALLOW_COPY_AND_ASSIGN(ScopedProcessInformation
);
106 #endif // BASE_WIN_SCOPED_PROCESS_INFORMATION_H_