Darin Petkov | 5a85047 | 2012-06-06 15:44:24 +0200 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium OS 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 | #ifndef SHILL_PROCESS_KILLER_H_ |
| 6 | #define SHILL_PROCESS_KILLER_H_ |
| 7 | |
| 8 | #include <map> |
| 9 | |
| 10 | #include <base/callback.h> |
| 11 | #include <base/lazy_instance.h> |
| 12 | #include <glib.h> |
| 13 | #include <gtest/gtest_prod.h> // for FRIEND_TEST |
| 14 | |
| 15 | namespace shill { |
| 16 | |
| 17 | // The ProcessKiller singleton can be used to asynchronously and robustly |
| 18 | // terminate and reap child processes by their process IDs. |
| 19 | class ProcessKiller { |
| 20 | public: |
| 21 | virtual ~ProcessKiller(); |
| 22 | |
| 23 | // This is a singleton -- use ProcessKiller::GetInstance()->Foo() |
| 24 | static ProcessKiller *GetInstance(); |
| 25 | |
Darin Petkov | 3806676 | 2012-12-17 15:35:45 +0100 | [diff] [blame] | 26 | // Uses GLib to wait asynchronously for the process to exit and reap it. GLib |
| 27 | // supports only a single callback per process ID so there should be no other |
| 28 | // child watch callbacks registered for this |pid|. If |callback| is non-null, |
Darin Petkov | 84a9553 | 2013-03-13 12:24:45 +0100 | [diff] [blame] | 29 | // runs it when the process exits. Returns false if the process has already |
| 30 | // exited. |
| 31 | virtual bool Wait(int pid, const base::Closure &callback); |
Darin Petkov | 3806676 | 2012-12-17 15:35:45 +0100 | [diff] [blame] | 32 | |
| 33 | // Terminates process |pid| and reaps it through Wait(pid, callback). |
Darin Petkov | 5a85047 | 2012-06-06 15:44:24 +0200 | [diff] [blame] | 34 | virtual void Kill(int pid, const base::Closure &callback); |
| 35 | |
| 36 | protected: |
| 37 | ProcessKiller(); |
| 38 | |
| 39 | private: |
| 40 | friend struct base::DefaultLazyInstanceTraits<ProcessKiller>; |
| 41 | FRIEND_TEST(ProcessKillerTest, OnProcessDied); |
| 42 | |
| 43 | static void OnProcessDied(GPid pid, gint status, gpointer data); |
| 44 | |
| 45 | std::map<int, base::Closure> callbacks_; |
| 46 | |
| 47 | DISALLOW_COPY_AND_ASSIGN(ProcessKiller); |
| 48 | }; |
| 49 | |
| 50 | } // namespace shill |
| 51 | |
| 52 | #endif // SHILL_PROCESS_KILLER_H_ |