OLD | NEW |
(Empty) | |
| 1 // 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 #include "chrome/common/process_watcher.h" |
| 6 |
| 7 #include <errno.h> |
| 8 #include <signal.h> |
| 9 #include <sys/types.h> |
| 10 #include <sys/wait.h> |
| 11 |
| 12 #include "base/platform_thread.h" |
| 13 |
| 14 // Return true if the given child is dead. This will also reap the process. |
| 15 // Doesn't block. |
| 16 static bool IsChildDead(pid_t child) { |
| 17 const int result = waitpid(child, NULL, WNOHANG); |
| 18 if (result == -1) { |
| 19 NOTREACHED(); |
| 20 } else if (result > 0) { |
| 21 // The child has died. |
| 22 return true; |
| 23 } |
| 24 |
| 25 return false; |
| 26 } |
| 27 |
| 28 // A thread class which waits for the given child to exit and reaps it. |
| 29 // If the child doesn't exit within a couple of seconds, kill it. |
| 30 class BackgroundReaper : public PlatformThread::Delegate { |
| 31 public: |
| 32 explicit BackgroundReaper(pid_t child) |
| 33 : child_(child) { |
| 34 } |
| 35 |
| 36 void ThreadMain() { |
| 37 WaitForChildToDie(); |
| 38 delete this; |
| 39 } |
| 40 |
| 41 void WaitForChildToDie() { |
| 42 // There's no good way to wait for a specific child to exit in a timed |
| 43 // fashion. (No kqueue on Linux), so we just loop and sleep. |
| 44 |
| 45 // Waits 0.5 * 4 = 2 seconds. |
| 46 for (unsigned i = 0; i < 4; ++i) { |
| 47 PlatformThread::Sleep(500); // 0.5 seconds |
| 48 if (IsChildDead(child_)) |
| 49 return; |
| 50 } |
| 51 |
| 52 if (kill(child_, SIGKILL) == 0) { |
| 53 // SIGKILL is uncatchable. Since the signal was delivered, we can |
| 54 // just wait for the process to die now in a blocking manner. |
| 55 int result; |
| 56 do { |
| 57 result = waitpid(child_, NULL, 0); |
| 58 } while (result == -1 && errno == EINTR); |
| 59 } else { |
| 60 LOG(ERROR) << "While waiting for " << child_ << " to terminate we" |
| 61 << " failed to deliver a SIGKILL signal (" << errno << ")."; |
| 62 } |
| 63 } |
| 64 |
| 65 private: |
| 66 const pid_t child_; |
| 67 |
| 68 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper); |
| 69 }; |
| 70 |
| 71 // static |
| 72 void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process) { |
| 73 // If the child is already dead, then there's nothing to do |
| 74 if (IsChildDead(process)) |
| 75 return; |
| 76 |
| 77 BackgroundReaper* reaper = new BackgroundReaper(process); |
| 78 PlatformThread::CreateNonJoinable(0, reaper); |
| 79 } |
OLD | NEW |