1 // Copyright (c) 2013 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.
5 #include "base/process/kill.h"
12 #include "base/file_util.h"
13 #include "base/logging.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/process/process_iterator.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
18 #include "base/threading/platform_thread.h"
24 int WaitpidWithTimeout(ProcessHandle handle,
25 int64 wait_milliseconds,
27 // This POSIX version of this function only guarantees that we wait no less
28 // than |wait_milliseconds| for the process to exit. The child process may
29 // exit sometime before the timeout has ended but we may still block for up
30 // to 256 milliseconds after the fact.
32 // waitpid() has no direct support on POSIX for specifying a timeout, you can
33 // either ask it to block indefinitely or return immediately (WNOHANG).
34 // When a child process terminates a SIGCHLD signal is sent to the parent.
35 // Catching this signal would involve installing a signal handler which may
36 // affect other parts of the application and would be difficult to debug.
38 // Our strategy is to call waitpid() once up front to check if the process
39 // has already exited, otherwise to loop for wait_milliseconds, sleeping for
40 // at most 256 milliseconds each time using usleep() and then calling
41 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
42 // we double it every 4 sleep cycles.
44 // usleep() is speced to exit if a signal is received for which a handler
45 // has been installed. This means that when a SIGCHLD is sent, it will exit
46 // depending on behavior external to this function.
48 // This function is used primarily for unit tests, if we want to use it in
49 // the application itself it would probably be best to examine other routes.
51 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
52 static const int64 kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
53 int64 max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
54 int64 double_sleep_time = 0;
56 // If the process hasn't exited yet, then sleep and try again.
57 TimeTicks wakeup_time = TimeTicks::Now() +
58 TimeDelta::FromMilliseconds(wait_milliseconds);
59 while (ret_pid == 0) {
60 TimeTicks now = TimeTicks::Now();
61 if (now > wakeup_time)
63 // Guaranteed to be non-negative!
64 int64 sleep_time_usecs = (wakeup_time - now).InMicroseconds();
65 // Sleep for a bit while we wait for the process to finish.
66 if (sleep_time_usecs > max_sleep_time_usecs)
67 sleep_time_usecs = max_sleep_time_usecs;
69 // usleep() will return 0 and set errno to EINTR on receipt of a signal
71 usleep(sleep_time_usecs);
72 ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
74 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
75 (double_sleep_time++ % 4 == 0)) {
76 max_sleep_time_usecs *= 2;
81 *success = (ret_pid != -1);
86 TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
90 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
91 can_block ? 0 : WNOHANG));
93 DPLOG(ERROR) << "waitpid(" << handle << ")";
96 return TERMINATION_STATUS_NORMAL_TERMINATION;
97 } else if (result == 0) {
98 // the child hasn't exited yet.
101 return TERMINATION_STATUS_STILL_RUNNING;
107 if (WIFSIGNALED(status)) {
108 switch (WTERMSIG(status)) {
114 return TERMINATION_STATUS_PROCESS_CRASHED;
118 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
124 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
125 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
127 return TERMINATION_STATUS_NORMAL_TERMINATION;
132 // Attempts to kill the process identified by the given process
133 // entry structure. Ignores specified exit_code; posix can't force that.
134 // Returns true if this is successful, false otherwise.
135 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
136 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
139 bool result = kill(process_id, SIGTERM) == 0;
140 if (result && wait) {
143 if (RunningOnValgrind()) {
144 // Wait for some extra time when running under Valgrind since the child
145 // processes may take some time doing leak checking.
149 unsigned sleep_ms = 4;
151 // The process may not end immediately due to pending I/O
153 while (tries-- > 0) {
154 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
155 if (pid == process_id) {
160 if (errno == ECHILD) {
161 // The wait may fail with ECHILD if another process also waited for
162 // the same pid, causing the process state to get cleaned up.
166 DPLOG(ERROR) << "Error waiting for process " << process_id;
169 usleep(sleep_ms * 1000);
170 const unsigned kMaxSleepMs = 1000;
171 if (sleep_ms < kMaxSleepMs)
175 // If we're waiting and the child hasn't died by now, force it
178 result = kill(process_id, SIGKILL) == 0;
182 DPLOG(ERROR) << "Unable to terminate process " << process_id;
187 bool KillProcessGroup(ProcessHandle process_group_id) {
188 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
190 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
194 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
195 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
198 TerminationStatus GetKnownDeadTerminationStatus(ProcessHandle handle,
200 bool result = kill(handle, SIGKILL) == 0;
203 DPLOG(ERROR) << "Unable to terminate process " << handle;
205 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
208 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
210 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
215 if (WIFEXITED(status)) {
216 *exit_code = WEXITSTATUS(status);
220 // If it didn't exit cleanly, it must have been signaled.
221 DCHECK(WIFSIGNALED(status));
225 bool WaitForExitCodeWithTimeout(ProcessHandle handle,
227 base::TimeDelta timeout) {
228 bool waitpid_success = false;
229 int status = WaitpidWithTimeout(handle, timeout.InMilliseconds(),
233 if (!waitpid_success)
235 if (WIFSIGNALED(status)) {
239 if (WIFEXITED(status)) {
240 *exit_code = WEXITSTATUS(status);
246 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
247 base::TimeDelta wait,
248 const ProcessFilter* filter) {
251 // TODO(port): This is inefficient, but works if there are multiple procs.
252 // TODO(port): use waitpid to avoid leaving zombies around
254 base::TimeTicks end_time = base::TimeTicks::Now() + wait;
256 NamedProcessIterator iter(executable_name, filter);
257 if (!iter.NextProcessEntry()) {
261 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
262 } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta());
267 #if defined(OS_MACOSX)
268 // Using kqueue on Mac so that we can wait on non-child processes.
269 // We can't use kqueues on child processes because we need to reap
270 // our own children using wait.
271 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
272 base::TimeDelta wait) {
273 DCHECK_GT(handle, 0);
274 DCHECK(wait.InMilliseconds() == base::kNoTimeout || wait > base::TimeDelta());
278 DPLOG(ERROR) << "kqueue";
281 file_util::ScopedFD kq_closer(&kq);
283 struct kevent change = {0};
284 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
285 int result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL));
287 if (errno == ESRCH) {
288 // If the process wasn't found, it must be dead.
292 DPLOG(ERROR) << "kevent (setup " << handle << ")";
296 // Keep track of the elapsed time to be able to restart kevent if it's
298 bool wait_forever = wait.InMilliseconds() == base::kNoTimeout;
299 base::TimeDelta remaining_delta;
300 base::TimeTicks deadline;
302 remaining_delta = wait;
303 deadline = base::TimeTicks::Now() + remaining_delta;
307 struct kevent event = {0};
309 while (wait_forever || remaining_delta > base::TimeDelta()) {
310 struct timespec remaining_timespec;
311 struct timespec* remaining_timespec_ptr;
313 remaining_timespec_ptr = NULL;
315 remaining_timespec = remaining_delta.ToTimeSpec();
316 remaining_timespec_ptr = &remaining_timespec;
319 result = kevent(kq, NULL, 0, &event, 1, remaining_timespec_ptr);
321 if (result == -1 && errno == EINTR) {
323 remaining_delta = deadline - base::TimeTicks::Now();
332 DPLOG(ERROR) << "kevent (wait " << handle << ")";
334 } else if (result > 1) {
335 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
338 } else if (result == 0) {
343 DCHECK_EQ(result, 1);
345 if (event.filter != EVFILT_PROC ||
346 (event.fflags & NOTE_EXIT) == 0 ||
347 event.ident != static_cast<uintptr_t>(handle)) {
348 DLOG(ERROR) << "kevent (wait " << handle
349 << "): unexpected event: filter=" << event.filter
350 << ", fflags=" << event.fflags
351 << ", ident=" << event.ident;
359 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
360 ProcessHandle parent_pid = GetParentProcessId(handle);
361 ProcessHandle our_pid = Process::Current().handle();
362 if (parent_pid != our_pid) {
363 #if defined(OS_MACOSX)
364 // On Mac we can wait on non child processes.
365 return WaitForSingleNonChildProcess(handle, wait);
367 // Currently on Linux we can't handle non child processes.
372 bool waitpid_success;
374 if (wait.InMilliseconds() == base::kNoTimeout) {
375 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
377 status = WaitpidWithTimeout(
378 handle, wait.InMilliseconds(), &waitpid_success);
382 DCHECK(waitpid_success);
383 return WIFEXITED(status);
389 bool CleanupProcesses(const FilePath::StringType& executable_name,
390 base::TimeDelta wait,
392 const ProcessFilter* filter) {
393 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
395 KillProcesses(executable_name, exit_code, filter);
396 return exited_cleanly;
399 #if !defined(OS_MACOSX)
403 // Return true if the given child is dead. This will also reap the process.
405 static bool IsChildDead(pid_t child) {
406 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
408 DPLOG(ERROR) << "waitpid(" << child << ")";
410 } else if (result > 0) {
411 // The child has died.
418 // A thread class which waits for the given child to exit and reaps it.
419 // If the child doesn't exit within a couple of seconds, kill it.
420 class BackgroundReaper : public PlatformThread::Delegate {
422 BackgroundReaper(pid_t child, unsigned timeout)
427 // Overridden from PlatformThread::Delegate:
428 virtual void ThreadMain() OVERRIDE {
433 void WaitForChildToDie() {
434 // Wait forever case.
436 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
438 DPLOG(ERROR) << "While waiting for " << child_
439 << " to terminate, we got the following result: " << r;
444 // There's no good way to wait for a specific child to exit in a timed
445 // fashion. (No kqueue on Linux), so we just loop and sleep.
447 // Wait for 2 * timeout_ 500 milliseconds intervals.
448 for (unsigned i = 0; i < 2 * timeout_; ++i) {
449 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
450 if (IsChildDead(child_))
454 if (kill(child_, SIGKILL) == 0) {
455 // SIGKILL is uncatchable. Since the signal was delivered, we can
456 // just wait for the process to die now in a blocking manner.
457 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
458 DPLOG(WARNING) << "waitpid";
460 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
461 << " failed to deliver a SIGKILL signal (" << errno << ").";
467 // Number of seconds to wait, if 0 then wait forever and do not attempt to
469 const unsigned timeout_;
471 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
476 void EnsureProcessTerminated(ProcessHandle process) {
477 // If the child is already dead, then there's nothing to do.
478 if (IsChildDead(process))
481 const unsigned timeout = 2; // seconds
482 BackgroundReaper* reaper = new BackgroundReaper(process, timeout);
483 PlatformThread::CreateNonJoinable(0, reaper);
486 void EnsureProcessGetsReaped(ProcessHandle process) {
487 // If the child is already dead, then there's nothing to do.
488 if (IsChildDead(process))
491 BackgroundReaper* reaper = new BackgroundReaper(process, 0);
492 PlatformThread::CreateNonJoinable(0, reaper);
495 #endif // !defined(OS_MACOSX)