blob: 70c367c75971ccac15959e71cf5524ce7d1dcbb3 [file] [log] [blame]
Darin Petkov5a850472012-06-06 15:44:24 +02001// 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
15namespace shill {
16
17// The ProcessKiller singleton can be used to asynchronously and robustly
18// terminate and reap child processes by their process IDs.
19class ProcessKiller {
20 public:
21 virtual ~ProcessKiller();
22
23 // This is a singleton -- use ProcessKiller::GetInstance()->Foo()
24 static ProcessKiller *GetInstance();
25
Darin Petkov38066762012-12-17 15:35:45 +010026 // 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 Petkov84a95532013-03-13 12:24:45 +010029 // 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 Petkov38066762012-12-17 15:35:45 +010032
33 // Terminates process |pid| and reaps it through Wait(pid, callback).
Darin Petkov5a850472012-06-06 15:44:24 +020034 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_