blob: 42ea876b73fce6deb00184492fa97915f9e2eb56 [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
mukesh agrawalf407d592013-07-31 11:37:57 -070023 // This is a singleton -- use ProcessKiller::GetInstance()->Foo().
Paul Stewart1a212a62015-06-16 13:13:10 -070024 static ProcessKiller* GetInstance();
Darin Petkov5a850472012-06-06 15:44:24 +020025
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.
Paul Stewart1a212a62015-06-16 13:13:10 -070031 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).
Paul Stewart1a212a62015-06-16 13:13:10 -070034 virtual void Kill(int pid, const base::Closure& callback);
Darin Petkov5a850472012-06-06 15:44:24 +020035
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_