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/files/file_util.h"
13 #include "base/files/scoped_file.h"
14 #include "base/logging.h"
15 #include "base/posix/eintr_wrapper.h"
16 #include "base/process/process_iterator.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
19 #include "base/threading/platform_thread.h"
25 #if !defined(OS_NACL_NONSFI)
26 bool WaitpidWithTimeout(ProcessHandle handle
,
28 base::TimeDelta wait
) {
29 // This POSIX version of this function only guarantees that we wait no less
30 // than |wait| for the process to exit. The child process may
31 // exit sometime before the timeout has ended but we may still block for up
32 // to 256 milliseconds after the fact.
34 // waitpid() has no direct support on POSIX for specifying a timeout, you can
35 // either ask it to block indefinitely or return immediately (WNOHANG).
36 // When a child process terminates a SIGCHLD signal is sent to the parent.
37 // Catching this signal would involve installing a signal handler which may
38 // affect other parts of the application and would be difficult to debug.
40 // Our strategy is to call waitpid() once up front to check if the process
41 // has already exited, otherwise to loop for |wait|, sleeping for
42 // at most 256 milliseconds each time using usleep() and then calling
43 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
44 // we double it every 4 sleep cycles.
46 // usleep() is speced to exit if a signal is received for which a handler
47 // has been installed. This means that when a SIGCHLD is sent, it will exit
48 // depending on behavior external to this function.
50 // This function is used primarily for unit tests, if we want to use it in
51 // the application itself it would probably be best to examine other routes.
53 if (wait
.InMilliseconds() == base::kNoTimeout
) {
54 return HANDLE_EINTR(waitpid(handle
, status
, 0)) > 0;
57 pid_t ret_pid
= HANDLE_EINTR(waitpid(handle
, status
, WNOHANG
));
58 static const int64 kMaxSleepInMicroseconds
= 1 << 18; // ~256 milliseconds.
59 int64 max_sleep_time_usecs
= 1 << 10; // ~1 milliseconds.
60 int64 double_sleep_time
= 0;
62 // If the process hasn't exited yet, then sleep and try again.
63 TimeTicks wakeup_time
= TimeTicks::Now() + wait
;
64 while (ret_pid
== 0) {
65 TimeTicks now
= TimeTicks::Now();
66 if (now
> wakeup_time
)
68 // Guaranteed to be non-negative!
69 int64 sleep_time_usecs
= (wakeup_time
- now
).InMicroseconds();
70 // Sleep for a bit while we wait for the process to finish.
71 if (sleep_time_usecs
> max_sleep_time_usecs
)
72 sleep_time_usecs
= max_sleep_time_usecs
;
74 // usleep() will return 0 and set errno to EINTR on receipt of a signal
76 usleep(sleep_time_usecs
);
77 ret_pid
= HANDLE_EINTR(waitpid(handle
, status
, WNOHANG
));
79 if ((max_sleep_time_usecs
< kMaxSleepInMicroseconds
) &&
80 (double_sleep_time
++ % 4 == 0)) {
81 max_sleep_time_usecs
*= 2;
88 #if defined(OS_MACOSX)
89 // Using kqueue on Mac so that we can wait on non-child processes.
90 // We can't use kqueues on child processes because we need to reap
91 // our own children using wait.
92 static bool WaitForSingleNonChildProcess(ProcessHandle handle
,
95 DCHECK(wait
.InMilliseconds() == kNoTimeout
|| wait
> TimeDelta());
97 ScopedFD
kq(kqueue());
99 DPLOG(ERROR
) << "kqueue";
103 struct kevent change
= {0};
104 EV_SET(&change
, handle
, EVFILT_PROC
, EV_ADD
, NOTE_EXIT
, 0, NULL
);
105 int result
= HANDLE_EINTR(kevent(kq
.get(), &change
, 1, NULL
, 0, NULL
));
107 if (errno
== ESRCH
) {
108 // If the process wasn't found, it must be dead.
112 DPLOG(ERROR
) << "kevent (setup " << handle
<< ")";
116 // Keep track of the elapsed time to be able to restart kevent if it's
118 bool wait_forever
= wait
.InMilliseconds() == kNoTimeout
;
119 TimeDelta remaining_delta
;
122 remaining_delta
= wait
;
123 deadline
= TimeTicks::Now() + remaining_delta
;
127 struct kevent event
= {0};
129 while (wait_forever
|| remaining_delta
> TimeDelta()) {
130 struct timespec remaining_timespec
;
131 struct timespec
* remaining_timespec_ptr
;
133 remaining_timespec_ptr
= NULL
;
135 remaining_timespec
= remaining_delta
.ToTimeSpec();
136 remaining_timespec_ptr
= &remaining_timespec
;
139 result
= kevent(kq
.get(), NULL
, 0, &event
, 1, remaining_timespec_ptr
);
141 if (result
== -1 && errno
== EINTR
) {
143 remaining_delta
= deadline
- TimeTicks::Now();
152 DPLOG(ERROR
) << "kevent (wait " << handle
<< ")";
154 } else if (result
> 1) {
155 DLOG(ERROR
) << "kevent (wait " << handle
<< "): unexpected result "
158 } else if (result
== 0) {
163 DCHECK_EQ(result
, 1);
165 if (event
.filter
!= EVFILT_PROC
||
166 (event
.fflags
& NOTE_EXIT
) == 0 ||
167 event
.ident
!= static_cast<uintptr_t>(handle
)) {
168 DLOG(ERROR
) << "kevent (wait " << handle
169 << "): unexpected event: filter=" << event
.filter
170 << ", fflags=" << event
.fflags
171 << ", ident=" << event
.ident
;
178 #endif // !defined(OS_NACL_NONSFI)
180 TerminationStatus
GetTerminationStatusImpl(ProcessHandle handle
,
184 const pid_t result
= HANDLE_EINTR(waitpid(handle
, &status
,
185 can_block
? 0 : WNOHANG
));
187 DPLOG(ERROR
) << "waitpid(" << handle
<< ")";
190 return TERMINATION_STATUS_NORMAL_TERMINATION
;
191 } else if (result
== 0) {
192 // the child hasn't exited yet.
195 return TERMINATION_STATUS_STILL_RUNNING
;
201 if (WIFSIGNALED(status
)) {
202 switch (WTERMSIG(status
)) {
208 return TERMINATION_STATUS_PROCESS_CRASHED
;
212 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
218 if (WIFEXITED(status
) && WEXITSTATUS(status
) != 0)
219 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
221 return TERMINATION_STATUS_NORMAL_TERMINATION
;
226 #if !defined(OS_NACL_NONSFI)
227 // Attempts to kill the process identified by the given process
228 // entry structure. Ignores specified exit_code; posix can't force that.
229 // Returns true if this is successful, false otherwise.
230 bool KillProcess(ProcessHandle process_id
, int exit_code
, bool wait
) {
231 DCHECK_GT(process_id
, 1) << " tried to kill invalid process_id";
234 bool result
= kill(process_id
, SIGTERM
) == 0;
235 if (result
&& wait
) {
238 if (RunningOnValgrind()) {
239 // Wait for some extra time when running under Valgrind since the child
240 // processes may take some time doing leak checking.
244 unsigned sleep_ms
= 4;
246 // The process may not end immediately due to pending I/O
248 while (tries
-- > 0) {
249 pid_t pid
= HANDLE_EINTR(waitpid(process_id
, NULL
, WNOHANG
));
250 if (pid
== process_id
) {
255 if (errno
== ECHILD
) {
256 // The wait may fail with ECHILD if another process also waited for
257 // the same pid, causing the process state to get cleaned up.
261 DPLOG(ERROR
) << "Error waiting for process " << process_id
;
264 usleep(sleep_ms
* 1000);
265 const unsigned kMaxSleepMs
= 1000;
266 if (sleep_ms
< kMaxSleepMs
)
270 // If we're waiting and the child hasn't died by now, force it
273 result
= kill(process_id
, SIGKILL
) == 0;
277 DPLOG(ERROR
) << "Unable to terminate process " << process_id
;
282 bool KillProcessGroup(ProcessHandle process_group_id
) {
283 bool result
= kill(-1 * process_group_id
, SIGKILL
) == 0;
285 DPLOG(ERROR
) << "Unable to terminate process group " << process_group_id
;
288 #endif // !defined(OS_NACL_NONSFI)
290 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
291 return GetTerminationStatusImpl(handle
, false /* can_block */, exit_code
);
294 TerminationStatus
GetKnownDeadTerminationStatus(ProcessHandle handle
,
296 bool result
= kill(handle
, SIGKILL
) == 0;
299 DPLOG(ERROR
) << "Unable to terminate process " << handle
;
301 return GetTerminationStatusImpl(handle
, true /* can_block */, exit_code
);
304 #if !defined(OS_NACL_NONSFI)
305 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
307 if (HANDLE_EINTR(waitpid(handle
, &status
, 0)) == -1) {
312 if (WIFEXITED(status
)) {
313 *exit_code
= WEXITSTATUS(status
);
317 // If it didn't exit cleanly, it must have been signaled.
318 DCHECK(WIFSIGNALED(status
));
322 bool WaitForExitCodeWithTimeout(ProcessHandle handle
,
325 ProcessHandle parent_pid
= GetParentProcessId(handle
);
326 ProcessHandle our_pid
= GetCurrentProcessHandle();
327 if (parent_pid
!= our_pid
) {
328 #if defined(OS_MACOSX)
329 // On Mac we can wait on non child processes.
330 return WaitForSingleNonChildProcess(handle
, timeout
);
332 // Currently on Linux we can't handle non child processes.
338 if (!WaitpidWithTimeout(handle
, &status
, timeout
))
340 if (WIFSIGNALED(status
)) {
344 if (WIFEXITED(status
)) {
345 *exit_code
= WEXITSTATUS(status
);
351 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
353 const ProcessFilter
* filter
) {
356 // TODO(port): This is inefficient, but works if there are multiple procs.
357 // TODO(port): use waitpid to avoid leaving zombies around
359 TimeTicks end_time
= TimeTicks::Now() + wait
;
361 NamedProcessIterator
iter(executable_name
, filter
);
362 if (!iter
.NextProcessEntry()) {
366 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
367 } while ((end_time
- TimeTicks::Now()) > TimeDelta());
372 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
375 const ProcessFilter
* filter
) {
376 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
378 KillProcesses(executable_name
, exit_code
, filter
);
379 return exited_cleanly
;
382 #if !defined(OS_MACOSX)
386 // Return true if the given child is dead. This will also reap the process.
388 static bool IsChildDead(pid_t child
) {
389 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
391 DPLOG(ERROR
) << "waitpid(" << child
<< ")";
393 } else if (result
> 0) {
394 // The child has died.
401 // A thread class which waits for the given child to exit and reaps it.
402 // If the child doesn't exit within a couple of seconds, kill it.
403 class BackgroundReaper
: public PlatformThread::Delegate
{
405 BackgroundReaper(pid_t child
, unsigned timeout
)
410 // Overridden from PlatformThread::Delegate:
411 void ThreadMain() override
{
416 void WaitForChildToDie() {
417 // Wait forever case.
419 pid_t r
= HANDLE_EINTR(waitpid(child_
, NULL
, 0));
421 DPLOG(ERROR
) << "While waiting for " << child_
422 << " to terminate, we got the following result: " << r
;
427 // There's no good way to wait for a specific child to exit in a timed
428 // fashion. (No kqueue on Linux), so we just loop and sleep.
430 // Wait for 2 * timeout_ 500 milliseconds intervals.
431 for (unsigned i
= 0; i
< 2 * timeout_
; ++i
) {
432 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
433 if (IsChildDead(child_
))
437 if (kill(child_
, SIGKILL
) == 0) {
438 // SIGKILL is uncatchable. Since the signal was delivered, we can
439 // just wait for the process to die now in a blocking manner.
440 if (HANDLE_EINTR(waitpid(child_
, NULL
, 0)) < 0)
441 DPLOG(WARNING
) << "waitpid";
443 DLOG(ERROR
) << "While waiting for " << child_
<< " to terminate we"
444 << " failed to deliver a SIGKILL signal (" << errno
<< ").";
450 // Number of seconds to wait, if 0 then wait forever and do not attempt to
452 const unsigned timeout_
;
454 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper
);
459 void EnsureProcessTerminated(Process process
) {
460 // If the child is already dead, then there's nothing to do.
461 if (IsChildDead(process
.Pid()))
464 const unsigned timeout
= 2; // seconds
465 BackgroundReaper
* reaper
= new BackgroundReaper(process
.Pid(), timeout
);
466 PlatformThread::CreateNonJoinable(0, reaper
);
469 void EnsureProcessGetsReaped(ProcessId pid
) {
470 // If the child is already dead, then there's nothing to do.
471 if (IsChildDead(pid
))
474 BackgroundReaper
* reaper
= new BackgroundReaper(pid
, 0);
475 PlatformThread::CreateNonJoinable(0, reaper
);
478 #endif // !defined(OS_MACOSX)
479 #endif // !defined(OS_NACL_NONSFI)