init: Allows shutting down cleanly.

When ro.build.shutdown_timeout is set, init will send a SIGTERM signal to
all services on reboot. The normal shutdown process will continue once
all services have exited or after the shutdown timeout
(ro.build.shutdown_timeout).

If ro.build.shutdown_timeout is not set, we assume a 0s timeout.

Bug: 26216447
Test: manual: Ask to reboot. All services exit cleanly.

Change-Id: If921f6e8d87211e500ac9fa86f3e1eabe02d18cf
diff --git a/init/service.h b/init/service.h
index 10eb736..35abde9 100644
--- a/init/service.h
+++ b/init/service.h
@@ -82,6 +82,7 @@
     bool Enable();
     void Reset();
     void Stop();
+    void Terminate();
     void Restart();
     void RestartIfNeeded(time_t& process_needs_restart);
     bool Reap();
@@ -167,17 +168,22 @@
     Service* FindServiceByName(const std::string& name) const;
     Service* FindServiceByPid(pid_t pid) const;
     Service* FindServiceByKeychord(int keychord_id) const;
-    void ForEachService(void (*func)(Service* svc)) const;
+    void ForEachService(std::function<void(Service*)> callback) const;
     void ForEachServiceInClass(const std::string& classname,
                                void (*func)(Service* svc)) const;
     void ForEachServiceWithFlags(unsigned matchflags,
                              void (*func)(Service* svc)) const;
+    void ReapAnyOutstandingChildren();
     void RemoveService(const Service& svc);
     void DumpState() const;
 
 private:
     ServiceManager();
 
+    // Cleans up a child process that exited.
+    // Returns true iff a children was cleaned up.
+    bool ReapOneProcess();
+
     static int exec_count_; // Every service needs a unique name.
     std::vector<std::unique_ptr<Service>> services_;
 };