blob: 92064a65aa5bb98f1e5634f1f7affe6a16de41eb [file] [log] [blame]
adlr@google.com3defe6a2009-12-04 20:57:17 +00001// Copyright (c) 2009 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.
4
5#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_SUBPROCESS_H__
6#define CHROMEOS_PLATFORM_UPDATE_ENGINE_SUBPROCESS_H__
7
8#include <map>
9#include <string>
10#include <vector>
11#include <glib.h>
12#include "chromeos/obsolete_logging.h"
13#include "base/basictypes.h"
14
15// The Subprocess class is a singleton. It's used to spawn off a subprocess
16// and get notified when the subprocess exits. The result of Exec() can
17// be saved and used to cancel the callback request. If you know you won't
18// call CancelExec(), you may safely lose the return value from Exec().
19
20namespace chromeos_update_engine {
21
22class Subprocess {
23 public:
24 static void Init() {
25 CHECK(!subprocess_singleton_);
26 subprocess_singleton_ = new Subprocess;
27 }
28
29 typedef void(*ExecCallback)(int return_code, void *p);
30
31 // Returns a tag > 0 on success.
32 uint32 Exec(const std::vector<std::string>& cmd,
33 ExecCallback callback,
34 void* p);
35
36 // Used to cancel the callback. The process will still run to completion.
37 void CancelExec(uint32 tag);
38
39 // Executes a command synchronously. Returns true on success.
40 static bool SynchronousExec(const std::vector<std::string>& cmd,
41 int* return_code);
42
43 // Gets the one instance
44 static Subprocess& Get() {
45 return *subprocess_singleton_;
46 }
47
48 // Returns true iff there is at least one subprocess we're waiting on.
49 bool SubprocessInFlight() {
50 for (std::map<int, SubprocessCallbackRecord>::iterator it =
51 callback_records_.begin();
52 it != callback_records_.end(); ++it) {
53 if (it->second.callback)
54 return true;
55 }
56 return false;
57 }
58 private:
59 // The global instance
60 static Subprocess* subprocess_singleton_;
61
62 // Callback for when any subprocess terminates. This calls the user
63 // requested callback.
64 static void GChildExitedCallback(GPid pid, gint status, gpointer data);
65
66 struct SubprocessCallbackRecord {
67 ExecCallback callback;
68 void* callback_data;
69 };
70
71 std::map<int, SubprocessCallbackRecord> callback_records_;
72
73 Subprocess() {}
74 DISALLOW_COPY_AND_ASSIGN(Subprocess);
75};
76
77} // namespace chromeos_update_engine
78
79#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_SUBPROCESS_H__