You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mesos.apache.org by be...@apache.org on 2013/08/06 08:08:34 UTC

[08/13] git commit: Added os::Fork for declaring and instantiating process trees.

Added os::Fork for declaring and instantiating process trees.

Review: https://reviews.apache.org/r/12432


Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/eb4762ca
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/eb4762ca
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/eb4762ca

Branch: refs/heads/master
Commit: eb4762ca38729a3a283ecaac3e07fa1112c24de4
Parents: 89a795b
Author: Benjamin Hindman <be...@twitter.com>
Authored: Tue Jun 25 13:05:16 2013 -0400
Committer: Benjamin Hindman <be...@gmail.com>
Committed: Mon Aug 5 23:08:04 2013 -0700

----------------------------------------------------------------------
 3rdparty/libprocess/3rdparty/stout/Makefile.am  |   1 +
 .../3rdparty/stout/include/stout/os.hpp         |   1 +
 .../3rdparty/stout/include/stout/os/fork.hpp    | 403 +++++++++++++++++++
 .../3rdparty/stout/include/stout/os/process.hpp |   1 +
 .../3rdparty/stout/tests/os_tests.cpp           | 335 +++------------
 5 files changed, 466 insertions(+), 275 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mesos/blob/eb4762ca/3rdparty/libprocess/3rdparty/stout/Makefile.am
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/Makefile.am b/3rdparty/libprocess/3rdparty/stout/Makefile.am
index b2ea5e6..770378d 100644
--- a/3rdparty/libprocess/3rdparty/stout/Makefile.am
+++ b/3rdparty/libprocess/3rdparty/stout/Makefile.am
@@ -35,6 +35,7 @@ EXTRA_DIST =					\
   include/stout/option.hpp			\
   include/stout/os.hpp				\
   include/stout/os/exists.hpp			\
+  include/stout/os/fork.hpp			\
   include/stout/os/killtree.hpp			\
   include/stout/os/linux.hpp			\
   include/stout/os/ls.hpp			\

http://git-wip-us.apache.org/repos/asf/mesos/blob/eb4762ca/3rdparty/libprocess/3rdparty/stout/include/stout/os.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/stout/os.hpp b/3rdparty/libprocess/3rdparty/stout/include/stout/os.hpp
index 53c0d33..448739e 100644
--- a/3rdparty/libprocess/3rdparty/stout/include/stout/os.hpp
+++ b/3rdparty/libprocess/3rdparty/stout/include/stout/os.hpp
@@ -51,6 +51,7 @@
 #include <stout/try.hpp>
 
 #include <stout/os/exists.hpp>
+#include <stout/os/fork.hpp>
 #include <stout/os/killtree.hpp>
 #ifdef __linux__
 #include <stout/os/linux.hpp>

http://git-wip-us.apache.org/repos/asf/mesos/blob/eb4762ca/3rdparty/libprocess/3rdparty/stout/include/stout/os/fork.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/stout/os/fork.hpp b/3rdparty/libprocess/3rdparty/stout/include/stout/os/fork.hpp
new file mode 100644
index 0000000..64e3b5d
--- /dev/null
+++ b/3rdparty/libprocess/3rdparty/stout/include/stout/os/fork.hpp
@@ -0,0 +1,403 @@
+#ifndef __STOUT_OS_FORK_HPP__
+#define __STOUT_OS_FORK_HPP__
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <list>
+#include <set>
+#include <string>
+
+#include <tr1/memory>
+
+#include <stout/error.hpp>
+#include <stout/exit.hpp>
+#include <stout/foreach.hpp>
+#include <stout/option.hpp>
+#include <stout/os.hpp>
+#include <stout/stringify.hpp>
+#include <stout/try.hpp>
+
+#include <stout/os/process.hpp>
+
+// Abstractions around forking process trees. You can declare a
+// process tree "template" using 'Fork', 'Exec', and 'Wait'. For
+// example, to describe a simple "fork/exec" you can do:
+//
+//   Fork f = Fork(Exec("sleep 10));
+//
+// The command passed to an 'Exec' is run via 'sh -c'. You can
+// construct more complicated templates via nesting, for example:
+//
+//   Fork f =
+//     Fork(None(),
+//          Fork(Exec("echo 'grandchild 1'")),
+//          Fork(None(),
+//               Fork(Exec("echo 'great-grandchild'")),
+//               Exec("echo 'grandchild 2'"))
+//          Exec("echo 'child'"));
+//
+// Note that the first argument to 'Fork' here is an optional function
+// that can be invoked before forking any more children or executing a
+// command. THIS FUNCTION SHOULD BE ASYNC SIGNAL SAFE.
+//
+// To wait for children, you can use 'Wait' instead of 'Exec', for
+// example:
+//
+//   Fork f =
+//     Fork(None(),
+//          Fork(Exec("echo 'grandchild 1'")),
+//          Fork(Exec("echo 'grandchild 2'")),
+//          Wait());
+//
+// You can also omit either an 'Exec' or a 'Wait' and the forked
+// process will just 'exit(0)'. For example, the following will cause
+// to processes to get reparented by 'init'.
+//
+//   Fork f =
+//     Fork(None(),
+//          Fork(Exec("echo 'grandchild 1'")),
+//          Fork(Exec("echo 'grandchild 2'")));
+//
+// A template can be instantiated by invoking the 'Fork' as a
+// functor. For example, using any of the templates above we can do:
+//
+//   Try<ProcessTree> tree = f();
+//
+// It's important to note that the process tree returned represents
+// the instant in time after the forking has completed but before
+// 'Exec', 'Wait' or 'exit(0)' has occured (i.e., the process tree
+// will be complete).
+
+namespace os {
+
+// Forward declaration.
+inline Result<Process> process(pid_t);
+
+
+struct Exec
+{
+  Exec(const std::string& _command)
+    : command(_command) {}
+
+  const std::string command;
+};
+
+
+struct Wait {};
+
+
+struct Fork
+{
+  //  -+- parent
+  Fork(const Option<void(*)(void)>& _function,
+       const Exec& _exec)
+    : function(_function),
+      exec(_exec) {}
+
+  Fork(const Exec& _exec) : exec(_exec) {}
+
+  //  -+- parent
+  //   \--- child
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1)
+    : function(_function)
+  {
+    children.push_back(fork1);
+  }
+
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Exec& _exec)
+    : function(_function),
+      exec(_exec)
+  {
+    children.push_back(fork1);
+  }
+
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Wait& _wait)
+    : function(_function),
+      wait(_wait)
+  {
+    children.push_back(fork1);
+  }
+
+  //  -+- parent
+  //   |--- child
+  //   \--- child
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Fork& fork2)
+    : function(_function)
+  {
+    children.push_back(fork1);
+    children.push_back(fork2);
+  }
+
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Fork& fork2,
+       const Exec& _exec)
+    : function(_function),
+      exec(_exec)
+  {
+    children.push_back(fork1);
+    children.push_back(fork2);
+  }
+
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Fork& fork2,
+       const Wait& _wait)
+    : function(_function),
+      wait(_wait)
+  {
+    children.push_back(fork1);
+    children.push_back(fork2);
+  }
+
+  //  -+- parent
+  //   |--- child
+  //   |--- child
+  //   \--- child
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Fork& fork2,
+       const Fork& fork3)
+    : function(_function)
+  {
+    children.push_back(fork1);
+    children.push_back(fork2);
+    children.push_back(fork3);
+  }
+
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Fork& fork2,
+       const Fork& fork3,
+       const Exec& _exec)
+    : function(_function),
+      exec(_exec)
+  {
+    children.push_back(fork1);
+    children.push_back(fork2);
+    children.push_back(fork3);
+  }
+
+  Fork(const Option<void(*)(void)>& _function,
+       const Fork& fork1,
+       const Fork& fork2,
+       const Fork& fork3,
+       const Wait& _wait)
+    : function(_function),
+      wait(_wait)
+  {
+    children.push_back(fork1);
+    children.push_back(fork2);
+    children.push_back(fork3);
+  }
+
+private:
+  // We use shared memory to "share" the pids of forked descendants.
+  // The benefit of shared memory over pipes is that each forked
+  // process can read its descendants' pids leading to a simpler
+  // implementation (with pipes, only one reader can ever read the
+  // value from the pipe, forcing much more complicated coordination).
+  //
+  // Shared memory works like a file (in memory) that gets deleted by
+  // "unlinking" it, but it won't get completely deleted until all
+  // open file descriptors referencing it have been closed. Each
+  // forked process has the shared memory mapped into it as well as an
+  // open file descriptor, both of which should get cleaned up
+  // automagically when the process exits, but we use a special
+  // "deleter" (in combination with shared_ptr) in order to clean this
+  // stuff up when we are actually finished using the shared memory.
+  struct SharedMemoryDeleter
+  {
+    SharedMemoryDeleter(int _fd) : fd(_fd) {}
+
+    void operator () (pid_t* pid) const
+    {
+      if (munmap(pid, sizeof(pid_t)) == -1) {
+        perror("Failed to unmap memory");
+        abort();
+      }
+      if (::close(fd) == -1) {
+        perror("Failed to close shared memory file descriptor");
+        abort();
+      }
+    }
+
+    const int fd;
+  };
+
+  // Represents the "tree" of descendants where each node has a
+  // pointer (into shared memory) from which we can read the
+  // descendants pid as well as a vector of children.
+  struct Tree
+  {
+    std::tr1::shared_ptr<pid_t> pid;
+    std::vector<Tree> children;
+  };
+
+  // Constructs a Tree (see above) from this fork template.
+  Try<Tree> prepare() const
+  {
+    static int forks = 0;
+
+    // Each "instance" of an instantiated Fork needs a unique name for
+    // creating shared memory.
+    int instance = __sync_fetch_and_add(&forks, 1);
+
+    std::string name =
+      "/stout-forks-" + stringify(getpid()) + stringify(instance);
+
+    int fd = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+
+    if (fd == -1) {
+      return ErrnoError("Failed to open a shared memory object");
+    }
+
+    if (ftruncate(fd, sizeof(pid_t)) == -1) {
+      return ErrnoError("Failed to set size of shared memory object");
+    }
+
+    void* memory = mmap(
+        NULL, sizeof(pid_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+
+    if (memory == MAP_FAILED) {
+      return ErrnoError("Failed to map shared memory object");
+    }
+
+    if (shm_unlink(name.c_str()) == -1) {
+      return ErrnoError("Failed to unlink shared memory object");
+    }
+
+    SharedMemoryDeleter deleter(fd);
+
+    Tree tree;
+    tree.pid = std::tr1::shared_ptr<pid_t>((pid_t*) memory, deleter);
+    *tree.pid = -1;
+
+    for (size_t i = 0; i < children.size(); i++) {
+      Try<Tree> tree_ = children[i].prepare();
+      if (tree_.isError()) {
+        return Error(tree_.error());
+      }
+      tree.children.push_back(tree_.get());
+    }
+
+    return tree;
+  }
+
+  // Performs the fork, executes the function, recursively
+  // instantiates any children, and then executes/waits/exits.
+  pid_t instantiate(const Tree& tree) const
+  {
+    pid_t pid = ::fork();
+    if (pid > 0) {
+      *tree.pid = pid;
+      return pid;
+    }
+
+    // Child process.
+
+    // Execute the function, if any.
+    if (function.isSome()) {
+      function.get()();
+    }
+
+    // Fork the children, if any.
+    CHECK(children.size() == tree.children.size());
+    std::set<pid_t> pids;
+    for (size_t i = 0; i < children.size(); i++) {
+      pids.insert(children[i].instantiate(tree.children[i]));
+    }
+
+    // Execute or wait.
+    if (exec.isSome()) {
+      // Execute the command (via '/bin/sh -c command').
+      const char* command = exec.get().command.c_str();
+      execl("/bin/sh", "sh", "-c", command, (char*) NULL);
+      EXIT(1) << "Failed to execute '" << command << "': " << strerror(errno);
+    } else if (wait.isSome()) {
+      foreach (pid_t pid, pids) {
+        // TODO(benh): Check for signal interruption or other errors.
+        waitpid(pid, NULL, 0);
+      }
+    }
+
+    exit(0);
+    return -1;
+  }
+
+  // Waits for all of the descendant processes in the tree to update
+  // their pids and constructs a ProcessTree by calling os::process
+  // for each pid.
+  static Try<ProcessTree> coordinate(const Tree& tree)
+  {
+    // Wait for the forked process.
+    // TODO(benh): Don't wait forever?
+    while (*tree.pid == -1) {
+      // Make sure we don't keep reading the value from a register.
+      __sync_synchronize();
+    }
+
+    Result<Process> process = os::process(*tree.pid);
+
+    if (process.isError()) {
+      return Error(process.error());
+    } else if (process.isNone()) {
+      // TODO(benh): Use a duplicate of the current process with
+      // 'tree.pid' instead, or consider copying the 'Process' struct
+      // via shared memory instead of just the pid.
+      return Error("Process already terminated");
+    }
+
+    std::list<ProcessTree> children;
+    for (size_t i = 0; i < tree.children.size(); i++) {
+      Try<ProcessTree> child = coordinate(tree.children[i]);
+      if (child.isError()) {
+        return Error(child.error());
+      }
+      children.push_back(child.get());
+    }
+
+    return ProcessTree(process.get(), children);
+  }
+
+public:
+  // Prepares and instantiates the process tree.
+  Try<ProcessTree> operator () () const
+  {
+    Try<Tree> tree = prepare();
+
+    if (tree.isError()) {
+      return Error(tree.error());
+    }
+
+    Try<pid_t> pid = instantiate(tree.get());
+
+    if (pid.isError()) {
+      return Error(pid.error());
+    }
+
+    return coordinate(tree.get());
+  }
+
+private:
+  Option<void(*)(void)> function;
+  Option<const Exec> exec;
+  Option<const Wait> wait;
+  std::vector<Fork> children;
+};
+
+} // namespace os {
+
+#endif // __STOUT_OS_FORK_HPP__

http://git-wip-us.apache.org/repos/asf/mesos/blob/eb4762ca/3rdparty/libprocess/3rdparty/stout/include/stout/os/process.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/stout/os/process.hpp b/3rdparty/libprocess/3rdparty/stout/include/stout/os/process.hpp
index b96715b..9dbb89f 100644
--- a/3rdparty/libprocess/3rdparty/stout/include/stout/os/process.hpp
+++ b/3rdparty/libprocess/3rdparty/stout/include/stout/os/process.hpp
@@ -99,6 +99,7 @@ public:
   const std::list<ProcessTree> children;
 
 private:
+  friend struct Fork;
   friend Try<ProcessTree> pstree(pid_t, const std::list<Process>&);
 
   ProcessTree(

http://git-wip-us.apache.org/repos/asf/mesos/blob/eb4762ca/3rdparty/libprocess/3rdparty/stout/tests/os_tests.cpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/tests/os_tests.cpp b/3rdparty/libprocess/3rdparty/stout/tests/os_tests.cpp
index 38ee01a..25f8444 100644
--- a/3rdparty/libprocess/3rdparty/stout/tests/os_tests.cpp
+++ b/3rdparty/libprocess/3rdparty/stout/tests/os_tests.cpp
@@ -20,6 +20,11 @@
 #include <stout/os/sysctl.hpp>
 #endif
 
+using os::Exec;
+using os::Fork;
+using os::Process;
+using os::ProcessTree;
+
 using std::list;
 using std::set;
 using std::string;
@@ -285,63 +290,16 @@ TEST_F(OsTest, children)
   ASSERT_SOME(children);
   EXPECT_EQ(0u, children.get().size());
 
-  // Use pipes to determine the pids of the grandchild.
-  int childPipes[2];
-  int grandchildPipes[2];
-  ASSERT_NE(-1, pipe(childPipes));
-  ASSERT_NE(-1, pipe(grandchildPipes));
-
-  pid_t grandchild;
-  pid_t child = fork();
-  ASSERT_NE(-1, child);
-
-  if (child > 0) {
-    // In parent process.
-    close(childPipes[1]);
-    close(grandchildPipes[1]);
-
-    // Get the pids via the pipes.
-    ASSERT_NE(-1, read(childPipes[0], &child, sizeof(child)));
-    ASSERT_NE(-1, read(grandchildPipes[0], &grandchild, sizeof(grandchild)));
-
-    close(childPipes[0]);
-    close(grandchildPipes[0]);
-  } else {
-    // In child process.
-    close(childPipes[0]);
-    close(grandchildPipes[0]);
-
-    // Double fork!
-    if ((grandchild = fork()) == -1) {
-      perror("Failed to fork a grandchild process");
-      abort();
-    }
+  Try<ProcessTree> tree =
+    Fork(None(),                   // Child.
+         Fork(Exec("sleep 10")),   // Grandchild.
+         Exec("sleep 10"))();
 
-    if (grandchild > 0) {
-      // Still in child process.
-      close(grandchildPipes[1]);
-
-      child = getpid();
-      if (write(childPipes[1], &child, sizeof(child)) != sizeof(child)) {
-        perror("Failed to write PID on pipe");
-        abort();
-      }
-      close(childPipes[1]);
-
-      while (true); // Keep waiting until we get a signal.
-    } else {
-      // In grandchild process.
-      grandchild = getpid();
-      if (write(grandchildPipes[1], &grandchild, sizeof(grandchild)) !=
-          sizeof(grandchild)) {
-        perror("Failed to write PID on pipe");
-        abort();
-      }
-      close(grandchildPipes[1]);
-
-      while (true); // Keep waiting until we get a signal.
-    }
-  }
+  ASSERT_SOME(tree);
+  ASSERT_EQ(1u, tree.get().children.size());
+
+  pid_t child = tree.get().process.pid;
+  pid_t grandchild = tree.get().children.front().process.pid;
 
   // Ensure the non-recursive children does not include the
   // grandchild.
@@ -369,7 +327,7 @@ TEST_F(OsTest, children)
 
 TEST_F(OsTest, process)
 {
-  const Result<os::Process>& status = os::process(getpid());
+  const Result<Process>& status = os::process(getpid());
 
   ASSERT_SOME(status);
   EXPECT_EQ(getpid(), status.get().pid);
@@ -392,14 +350,14 @@ TEST_F(OsTest, process)
 
 TEST_F(OsTest, processes)
 {
-  const Try<list<os::Process> >& processes = os::processes();
+  const Try<list<Process> >& processes = os::processes();
 
   ASSERT_SOME(processes);
   ASSERT_GT(processes.get().size(), 2);
 
   // Look for ourselves in the table.
   bool found = false;
-  foreach (const os::Process& process, processes.get()) {
+  foreach (const Process& process, processes.get()) {
     if (process.pid == getpid()) {
       found = true;
       EXPECT_EQ(getpid(), process.pid);
@@ -426,166 +384,41 @@ TEST_F(OsTest, processes)
 }
 
 
-TEST_F(OsTest, killtree) {
-  // Use pipes to determine the pids of the child and grandchild.
-  int childPipes[2];
-  int grandchildPipes[2];
-  int greatGrandchildPipes[2];
-  int greatGreatGrandchildPipes[2];
-
-  ASSERT_NE(-1, pipe(childPipes));
-  ASSERT_NE(-1, pipe(grandchildPipes));
-  ASSERT_NE(-1, pipe(greatGrandchildPipes));
-  ASSERT_NE(-1, pipe(greatGreatGrandchildPipes));
-
-  pid_t child;
-  pid_t grandchild;
-  pid_t greatGrandchild;
-  pid_t greatGreatGrandchild;
-
-  child = fork();
-  ASSERT_NE(-1, child);
-
-  // To test killtree, we create the following process chain:
-  // 1: This process.
-  // 2: Child process having called setsid().
-  // X: Grandchild process, terminates immediately after forking!
-  // 4: Great-grandchild process.
-  // 5: Great-great-grandchild process, calls setsid()!
-  // We expect killtree to kill 4 via its session or group.
-  // We also expect killtree to kill 5 via its parent process,
-  // despite having called setsid().
-  if (child > 0) {
-    // Parent.
-    close(childPipes[1]);
-    close(grandchildPipes[1]);
-    close(greatGrandchildPipes[1]);
-    close(greatGreatGrandchildPipes[1]);
-
-    // Get the pids via the pipes.
-    ASSERT_NE(-1, read(childPipes[0], &child, sizeof(child)));
-    ASSERT_NE(
-        -1,
-        read(grandchildPipes[0], &grandchild, sizeof(grandchild)));
-    ASSERT_NE(
-        -1,
-        read(greatGrandchildPipes[0],
-             &greatGrandchild,
-             sizeof(greatGrandchild)));
-    ASSERT_NE(
-        -1,
-        read(greatGreatGrandchildPipes[0],
-             &greatGreatGrandchild,
-             sizeof(greatGreatGrandchild)));
-
-    close(childPipes[0]);
-    close(grandchildPipes[0]);
-    close(greatGrandchildPipes[0]);
-    close(greatGreatGrandchildPipes[0]);
-  } else {
-    // --------------------------------------------------------------
-    // Child: setsid().
-    // --------------------------------------------------------------
-    close(childPipes[0]);
-    close(grandchildPipes[0]);
-    close(greatGrandchildPipes[0]);
-    close(greatGreatGrandchildPipes[0]);
-
-    if (setsid() == -1) {
-      perror("Failed to setsid in great-great-grandchild process");
-      abort();
-    }
-
-    child = getpid();
-    if (write(childPipes[1], &child, sizeof(child)) != sizeof(child)) {
-      perror("Failed to write child PID on pipe");
-      abort();
-    }
-    close(childPipes[1]);
-
-    if ((grandchild = fork()) == -1) {
-      perror("Failed to fork a grandchild process");
-      abort();
-    }
-
-    if (grandchild > 0) {
-      close(grandchildPipes[1]);
-      close(greatGrandchildPipes[1]);
-      close(greatGreatGrandchildPipes[1]);
-      while (true); // Await signal.
-    }
-
-    // --------------------------------------------------------------
-    // Grandchild: terminate.
-    // --------------------------------------------------------------
-    // Send the grandchild pid over the pipe.
-    grandchild = getpid();
-    if (write(grandchildPipes[1], &grandchild, sizeof(grandchild)) !=
-        sizeof(grandchild)) {
-      perror("Failed to write grandchild PID on pipe");
-      abort();
-    }
-    close(grandchildPipes[1]);
-
-    if ((greatGrandchild = fork()) == -1) {
-      perror("Failed to fork a great-grandchild process");
-      abort();
-    }
-
-    if (greatGrandchild > 0) {
-      // Terminate to break the parent link.
-      close(greatGrandchildPipes[1]);
-      close(greatGreatGrandchildPipes[1]);
-      exit(0);
-    }
-
-    // --------------------------------------------------------------
-    // Great-grandchild.
-    // --------------------------------------------------------------
-    // Send the Great-grandchild pid over the pipe.
-    greatGrandchild = getpid();
-    if (write(greatGrandchildPipes[1],
-              &greatGrandchild,
-              sizeof(greatGrandchild)) != sizeof(greatGrandchild)) {
-      perror("Failed to write great-grandchild PID on pipe");
-      abort();
-    }
-    close(greatGrandchildPipes[1]);
+void dosetsid(void)
+{
+  if (::setsid() == -1) {
+    perror("Failed to setsid");
+    abort();
+  }
+}
 
-    if ((greatGreatGrandchild = fork()) == -1) {
-      perror("Failed to fork a great-great-grandchild process");
-      abort();
-    }
 
-    if (greatGreatGrandchild > 0) {
-      // Great-grandchild.
-      close(greatGreatGrandchildPipes[1]);
-      while (true); // Await signal.
-    }
+TEST_F(OsTest, killtree)
+{
+  Try<ProcessTree> tree =
+    Fork(dosetsid,                         // Child.
+         Fork(None(),                      // Grandchild.
+              Fork(None(),                 // Great-grandchild.
+                   Fork(dosetsid,          // Great-great-granchild.
+                        Exec("sleep 10")),
+                   Exec("sleep 10")),
+              Exec("exit 0")),
+         Exec("sleep 10"))();
 
-    // --------------------------------------------------------------
-    // Great-great-grandchild: setsid().
-    // --------------------------------------------------------------
-    if (setsid() == -1) {
-      perror("Failed to setsid in great-great-grandchild process");
-      abort();
-    }
+  ASSERT_SOME(tree);
 
-    // Send the Great-great-grandchild pid over the pipe.
-    greatGreatGrandchild = getpid();
-    if (write(greatGreatGrandchildPipes[1],
-              &greatGreatGrandchild,
-              sizeof(greatGreatGrandchild)) != sizeof(greatGreatGrandchild)) {
-      perror("Failed to write great-great-grandchild PID on pipe");
-      abort();
-    }
-    close(greatGreatGrandchildPipes[1]);
+  ASSERT_EQ(1u, tree.get().children.size());
+  ASSERT_EQ(1u, tree.get().children.front().children.size());
+  ASSERT_EQ(1u, tree.get().children.front().children.front().children.size());
 
-    while (true); // Await signal.
-  }
+  pid_t child = tree.get();
+  pid_t grandchild = tree.get().children.front();
+  pid_t greatGrandchild = tree.get().children.front().children.front();
+  pid_t greatGreatGrandchild =
+    tree.get().children.front().children.front().children.front();
 
   // Kill the child process tree, this is expected to
-  // cross the broken link to the grandchild
+  // cross the broken link to the grandchild.
   EXPECT_SOME(os::killtree(child, SIGKILL, true, true, &std::cout));
 
   // There is a delay for the process to move into the zombie state.
@@ -605,78 +438,30 @@ TEST_F(OsTest, killtree) {
 
 TEST_F(OsTest, pstree)
 {
-  Try<os::ProcessTree> tree = os::pstree(0);
+  Try<ProcessTree> tree = os::pstree(getpid());
 
   ASSERT_SOME(tree);
   EXPECT_EQ(0u, tree.get().children.size());
 
-  // Use pipes to determine the pids of the grandchild.
-  int childPipes[2];
-  int grandchildPipes[2];
-  ASSERT_NE(-1, pipe(childPipes));
-  ASSERT_NE(-1, pipe(grandchildPipes));
-
-  pid_t grandchild;
-  pid_t child = fork();
-  ASSERT_NE(-1, child);
-
-  if (child > 0) {
-    // In parent process.
-    close(childPipes[1]);
-    close(grandchildPipes[1]);
-
-    // Get the pids via the pipes.
-    ASSERT_NE(-1, read(childPipes[0], &child, sizeof(child)));
-    ASSERT_NE(-1, read(grandchildPipes[0], &grandchild, sizeof(grandchild)));
-
-    close(childPipes[0]);
-    close(grandchildPipes[0]);
-  } else {
-    // In child process.
-    close(childPipes[0]);
-    close(grandchildPipes[0]);
-
-    // Double fork!
-    if ((grandchild = fork()) == -1) {
-      perror("Failed to fork a grandchild process");
-      abort();
-    }
+  tree =
+    Fork(None(),                   // Child.
+         Fork(Exec("sleep 10")),   // Grandchild.
+         Exec("sleep 10"))();
 
-    if (grandchild > 0) {
-      // Still in child process.
-      close(grandchildPipes[1]);
-
-      child = getpid();
-      if (write(childPipes[1], &child, sizeof(child)) != sizeof(child)) {
-        perror("Failed to write PID on pipe");
-        abort();
-      }
-      close(childPipes[1]);
-
-      while (true); // Keep waiting until we get a signal.
-    } else {
-      // In grandchild process.
-      grandchild = getpid();
-      if (write(grandchildPipes[1], &grandchild, sizeof(grandchild)) !=
-          sizeof(grandchild)) {
-        perror("Failed to write PID on pipe");
-        abort();
-      }
-      close(grandchildPipes[1]);
-
-      while (true); // Keep waiting until we get a signal.
-    }
-  }
+  ASSERT_SOME(tree);
+  ASSERT_EQ(1u, tree.get().children.size());
 
-  // Ensure the non-recursive children does not include the
-  // grandchild.
-  tree = os::pstree(0);
+  pid_t child = tree.get().process.pid;
+  pid_t grandchild = tree.get().children.front().process.pid;
+
+  // Now check pstree again.
+  tree = os::pstree(child);
 
   ASSERT_SOME(tree);
+  EXPECT_EQ(child, tree.get().process.pid);
+
   ASSERT_EQ(1u, tree.get().children.size());
-  EXPECT_EQ(child, tree.get().children.front().process.pid);
-  ASSERT_EQ(1u, tree.get().children.front().children.size());
-  EXPECT_EQ(grandchild, tree.get().children.front().children.front().process.pid);
+  EXPECT_EQ(grandchild, tree.get().children.front().process.pid);
 
   // Cleanup by killing the descendant processes.
   EXPECT_EQ(0, kill(grandchild, SIGKILL));