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;
87 #endif // !defined(OS_NACL_NONSFI)
89 TerminationStatus
GetTerminationStatusImpl(ProcessHandle handle
,
93 const pid_t result
= HANDLE_EINTR(waitpid(handle
, &status
,
94 can_block
? 0 : WNOHANG
));
96 DPLOG(ERROR
) << "waitpid(" << handle
<< ")";
99 return TERMINATION_STATUS_NORMAL_TERMINATION
;
100 } else if (result
== 0) {
101 // the child hasn't exited yet.
104 return TERMINATION_STATUS_STILL_RUNNING
;
110 if (WIFSIGNALED(status
)) {
111 switch (WTERMSIG(status
)) {
117 return TERMINATION_STATUS_PROCESS_CRASHED
;
121 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
127 if (WIFEXITED(status
) && WEXITSTATUS(status
) != 0)
128 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
130 return TERMINATION_STATUS_NORMAL_TERMINATION
;
135 #if !defined(OS_NACL_NONSFI)
136 // Attempts to kill the process identified by the given process
137 // entry structure. Ignores specified exit_code; posix can't force that.
138 // Returns true if this is successful, false otherwise.
139 bool KillProcess(ProcessHandle process_id
, int exit_code
, bool wait
) {
140 DCHECK_GT(process_id
, 1) << " tried to kill invalid process_id";
143 bool result
= kill(process_id
, SIGTERM
) == 0;
144 if (result
&& wait
) {
147 if (RunningOnValgrind()) {
148 // Wait for some extra time when running under Valgrind since the child
149 // processes may take some time doing leak checking.
153 unsigned sleep_ms
= 4;
155 // The process may not end immediately due to pending I/O
157 while (tries
-- > 0) {
158 pid_t pid
= HANDLE_EINTR(waitpid(process_id
, NULL
, WNOHANG
));
159 if (pid
== process_id
) {
164 if (errno
== ECHILD
) {
165 // The wait may fail with ECHILD if another process also waited for
166 // the same pid, causing the process state to get cleaned up.
170 DPLOG(ERROR
) << "Error waiting for process " << process_id
;
173 usleep(sleep_ms
* 1000);
174 const unsigned kMaxSleepMs
= 1000;
175 if (sleep_ms
< kMaxSleepMs
)
179 // If we're waiting and the child hasn't died by now, force it
182 result
= kill(process_id
, SIGKILL
) == 0;
186 DPLOG(ERROR
) << "Unable to terminate process " << process_id
;
191 bool KillProcessGroup(ProcessHandle process_group_id
) {
192 bool result
= kill(-1 * process_group_id
, SIGKILL
) == 0;
194 DPLOG(ERROR
) << "Unable to terminate process group " << process_group_id
;
197 #endif // !defined(OS_NACL_NONSFI)
199 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
200 return GetTerminationStatusImpl(handle
, false /* can_block */, exit_code
);
203 TerminationStatus
GetKnownDeadTerminationStatus(ProcessHandle handle
,
205 bool result
= kill(handle
, SIGKILL
) == 0;
208 DPLOG(ERROR
) << "Unable to terminate process " << handle
;
210 return GetTerminationStatusImpl(handle
, true /* can_block */, exit_code
);
213 #if !defined(OS_NACL_NONSFI)
214 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
216 if (HANDLE_EINTR(waitpid(handle
, &status
, 0)) == -1) {
221 if (WIFEXITED(status
)) {
222 *exit_code
= WEXITSTATUS(status
);
226 // If it didn't exit cleanly, it must have been signaled.
227 DCHECK(WIFSIGNALED(status
));
231 bool WaitForExitCodeWithTimeout(ProcessHandle handle
,
233 base::TimeDelta timeout
) {
235 if (!WaitpidWithTimeout(handle
, &status
, timeout
))
237 if (WIFSIGNALED(status
)) {
241 if (WIFEXITED(status
)) {
242 *exit_code
= WEXITSTATUS(status
);
248 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
249 base::TimeDelta wait
,
250 const ProcessFilter
* filter
) {
253 // TODO(port): This is inefficient, but works if there are multiple procs.
254 // TODO(port): use waitpid to avoid leaving zombies around
256 base::TimeTicks end_time
= base::TimeTicks::Now() + wait
;
258 NamedProcessIterator
iter(executable_name
, filter
);
259 if (!iter
.NextProcessEntry()) {
263 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
264 } while ((end_time
- base::TimeTicks::Now()) > base::TimeDelta());
269 #if defined(OS_MACOSX)
270 // Using kqueue on Mac so that we can wait on non-child processes.
271 // We can't use kqueues on child processes because we need to reap
272 // our own children using wait.
273 static bool WaitForSingleNonChildProcess(ProcessHandle handle
,
274 base::TimeDelta wait
) {
275 DCHECK_GT(handle
, 0);
276 DCHECK(wait
.InMilliseconds() == base::kNoTimeout
|| wait
> base::TimeDelta());
278 ScopedFD
kq(kqueue());
279 if (!kq
.is_valid()) {
280 DPLOG(ERROR
) << "kqueue";
284 struct kevent change
= {0};
285 EV_SET(&change
, handle
, EVFILT_PROC
, EV_ADD
, NOTE_EXIT
, 0, NULL
);
286 int result
= HANDLE_EINTR(kevent(kq
.get(), &change
, 1, NULL
, 0, NULL
));
288 if (errno
== ESRCH
) {
289 // If the process wasn't found, it must be dead.
293 DPLOG(ERROR
) << "kevent (setup " << handle
<< ")";
297 // Keep track of the elapsed time to be able to restart kevent if it's
299 bool wait_forever
= wait
.InMilliseconds() == base::kNoTimeout
;
300 base::TimeDelta remaining_delta
;
301 base::TimeTicks deadline
;
303 remaining_delta
= wait
;
304 deadline
= base::TimeTicks::Now() + remaining_delta
;
308 struct kevent event
= {0};
310 while (wait_forever
|| remaining_delta
> base::TimeDelta()) {
311 struct timespec remaining_timespec
;
312 struct timespec
* remaining_timespec_ptr
;
314 remaining_timespec_ptr
= NULL
;
316 remaining_timespec
= remaining_delta
.ToTimeSpec();
317 remaining_timespec_ptr
= &remaining_timespec
;
320 result
= kevent(kq
.get(), NULL
, 0, &event
, 1, remaining_timespec_ptr
);
322 if (result
== -1 && errno
== EINTR
) {
324 remaining_delta
= deadline
- base::TimeTicks::Now();
333 DPLOG(ERROR
) << "kevent (wait " << handle
<< ")";
335 } else if (result
> 1) {
336 DLOG(ERROR
) << "kevent (wait " << handle
<< "): unexpected result "
339 } else if (result
== 0) {
344 DCHECK_EQ(result
, 1);
346 if (event
.filter
!= EVFILT_PROC
||
347 (event
.fflags
& NOTE_EXIT
) == 0 ||
348 event
.ident
!= static_cast<uintptr_t>(handle
)) {
349 DLOG(ERROR
) << "kevent (wait " << handle
350 << "): unexpected event: filter=" << event
.filter
351 << ", fflags=" << event
.fflags
352 << ", ident=" << event
.ident
;
360 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
361 ProcessHandle parent_pid
= GetParentProcessId(handle
);
362 ProcessHandle our_pid
= GetCurrentProcessHandle();
363 if (parent_pid
!= our_pid
) {
364 #if defined(OS_MACOSX)
365 // On Mac we can wait on non child processes.
366 return WaitForSingleNonChildProcess(handle
, wait
);
368 // Currently on Linux we can't handle non child processes.
374 if (!WaitpidWithTimeout(handle
, &status
, wait
))
376 return WIFEXITED(status
);
379 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
380 base::TimeDelta wait
,
382 const ProcessFilter
* filter
) {
383 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
385 KillProcesses(executable_name
, exit_code
, filter
);
386 return exited_cleanly
;
389 #if !defined(OS_MACOSX)
393 // Return true if the given child is dead. This will also reap the process.
395 static bool IsChildDead(pid_t child
) {
396 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
398 DPLOG(ERROR
) << "waitpid(" << child
<< ")";
400 } else if (result
> 0) {
401 // The child has died.
408 // A thread class which waits for the given child to exit and reaps it.
409 // If the child doesn't exit within a couple of seconds, kill it.
410 class BackgroundReaper
: public PlatformThread::Delegate
{
412 BackgroundReaper(pid_t child
, unsigned timeout
)
417 // Overridden from PlatformThread::Delegate:
418 void ThreadMain() override
{
423 void WaitForChildToDie() {
424 // Wait forever case.
426 pid_t r
= HANDLE_EINTR(waitpid(child_
, NULL
, 0));
428 DPLOG(ERROR
) << "While waiting for " << child_
429 << " to terminate, we got the following result: " << r
;
434 // There's no good way to wait for a specific child to exit in a timed
435 // fashion. (No kqueue on Linux), so we just loop and sleep.
437 // Wait for 2 * timeout_ 500 milliseconds intervals.
438 for (unsigned i
= 0; i
< 2 * timeout_
; ++i
) {
439 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
440 if (IsChildDead(child_
))
444 if (kill(child_
, SIGKILL
) == 0) {
445 // SIGKILL is uncatchable. Since the signal was delivered, we can
446 // just wait for the process to die now in a blocking manner.
447 if (HANDLE_EINTR(waitpid(child_
, NULL
, 0)) < 0)
448 DPLOG(WARNING
) << "waitpid";
450 DLOG(ERROR
) << "While waiting for " << child_
<< " to terminate we"
451 << " failed to deliver a SIGKILL signal (" << errno
<< ").";
457 // Number of seconds to wait, if 0 then wait forever and do not attempt to
459 const unsigned timeout_
;
461 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper
);
466 void EnsureProcessTerminated(Process process
) {
467 // If the child is already dead, then there's nothing to do.
468 if (IsChildDead(process
.Pid()))
471 const unsigned timeout
= 2; // seconds
472 BackgroundReaper
* reaper
= new BackgroundReaper(process
.Pid(), timeout
);
473 PlatformThread::CreateNonJoinable(0, reaper
);
476 void EnsureProcessGetsReaped(ProcessId pid
) {
477 // If the child is already dead, then there's nothing to do.
478 if (IsChildDead(pid
))
481 BackgroundReaper
* reaper
= new BackgroundReaper(pid
, 0);
482 PlatformThread::CreateNonJoinable(0, reaper
);
485 #endif // !defined(OS_MACOSX)
486 #endif // !defined(OS_NACL_NONSFI)