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 TerminationStatus
GetTerminationStatusImpl(ProcessHandle handle
,
29 const pid_t result
= HANDLE_EINTR(waitpid(handle
, &status
,
30 can_block
? 0 : WNOHANG
));
32 DPLOG(ERROR
) << "waitpid(" << handle
<< ")";
35 return TERMINATION_STATUS_NORMAL_TERMINATION
;
36 } else if (result
== 0) {
37 // the child hasn't exited yet.
40 return TERMINATION_STATUS_STILL_RUNNING
;
46 if (WIFSIGNALED(status
)) {
47 switch (WTERMSIG(status
)) {
53 return TERMINATION_STATUS_PROCESS_CRASHED
;
57 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
63 if (WIFEXITED(status
) && WEXITSTATUS(status
) != 0)
64 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
66 return TERMINATION_STATUS_NORMAL_TERMINATION
;
71 #if !defined(OS_NACL_NONSFI)
72 // Attempts to kill the process identified by the given process
73 // entry structure. Ignores specified exit_code; posix can't force that.
74 // Returns true if this is successful, false otherwise.
75 bool KillProcess(ProcessHandle process_id
, int exit_code
, bool wait
) {
76 DCHECK_GT(process_id
, 1) << " tried to kill invalid process_id";
79 bool result
= kill(process_id
, SIGTERM
) == 0;
83 if (RunningOnValgrind()) {
84 // Wait for some extra time when running under Valgrind since the child
85 // processes may take some time doing leak checking.
89 unsigned sleep_ms
= 4;
91 // The process may not end immediately due to pending I/O
94 pid_t pid
= HANDLE_EINTR(waitpid(process_id
, NULL
, WNOHANG
));
95 if (pid
== process_id
) {
100 if (errno
== ECHILD
) {
101 // The wait may fail with ECHILD if another process also waited for
102 // the same pid, causing the process state to get cleaned up.
106 DPLOG(ERROR
) << "Error waiting for process " << process_id
;
109 usleep(sleep_ms
* 1000);
110 const unsigned kMaxSleepMs
= 1000;
111 if (sleep_ms
< kMaxSleepMs
)
115 // If we're waiting and the child hasn't died by now, force it
118 result
= kill(process_id
, SIGKILL
) == 0;
122 DPLOG(ERROR
) << "Unable to terminate process " << process_id
;
127 bool KillProcessGroup(ProcessHandle process_group_id
) {
128 bool result
= kill(-1 * process_group_id
, SIGKILL
) == 0;
130 DPLOG(ERROR
) << "Unable to terminate process group " << process_group_id
;
133 #endif // !defined(OS_NACL_NONSFI)
135 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
136 return GetTerminationStatusImpl(handle
, false /* can_block */, exit_code
);
139 TerminationStatus
GetKnownDeadTerminationStatus(ProcessHandle handle
,
141 bool result
= kill(handle
, SIGKILL
) == 0;
144 DPLOG(ERROR
) << "Unable to terminate process " << handle
;
146 return GetTerminationStatusImpl(handle
, true /* can_block */, exit_code
);
149 #if !defined(OS_NACL_NONSFI)
150 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
152 const ProcessFilter
* filter
) {
155 // TODO(port): This is inefficient, but works if there are multiple procs.
156 // TODO(port): use waitpid to avoid leaving zombies around
158 TimeTicks end_time
= TimeTicks::Now() + wait
;
160 NamedProcessIterator
iter(executable_name
, filter
);
161 if (!iter
.NextProcessEntry()) {
165 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
166 } while ((end_time
- TimeTicks::Now()) > TimeDelta());
171 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
174 const ProcessFilter
* filter
) {
175 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
177 KillProcesses(executable_name
, exit_code
, filter
);
178 return exited_cleanly
;
181 #if !defined(OS_MACOSX)
185 // Return true if the given child is dead. This will also reap the process.
187 static bool IsChildDead(pid_t child
) {
188 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
190 DPLOG(ERROR
) << "waitpid(" << child
<< ")";
192 } else if (result
> 0) {
193 // The child has died.
200 // A thread class which waits for the given child to exit and reaps it.
201 // If the child doesn't exit within a couple of seconds, kill it.
202 class BackgroundReaper
: public PlatformThread::Delegate
{
204 BackgroundReaper(pid_t child
, unsigned timeout
)
209 // Overridden from PlatformThread::Delegate:
210 void ThreadMain() override
{
215 void WaitForChildToDie() {
216 // Wait forever case.
218 pid_t r
= HANDLE_EINTR(waitpid(child_
, NULL
, 0));
220 DPLOG(ERROR
) << "While waiting for " << child_
221 << " to terminate, we got the following result: " << r
;
226 // There's no good way to wait for a specific child to exit in a timed
227 // fashion. (No kqueue on Linux), so we just loop and sleep.
229 // Wait for 2 * timeout_ 500 milliseconds intervals.
230 for (unsigned i
= 0; i
< 2 * timeout_
; ++i
) {
231 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
232 if (IsChildDead(child_
))
236 if (kill(child_
, SIGKILL
) == 0) {
237 // SIGKILL is uncatchable. Since the signal was delivered, we can
238 // just wait for the process to die now in a blocking manner.
239 if (HANDLE_EINTR(waitpid(child_
, NULL
, 0)) < 0)
240 DPLOG(WARNING
) << "waitpid";
242 DLOG(ERROR
) << "While waiting for " << child_
<< " to terminate we"
243 << " failed to deliver a SIGKILL signal (" << errno
<< ").";
249 // Number of seconds to wait, if 0 then wait forever and do not attempt to
251 const unsigned timeout_
;
253 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper
);
258 void EnsureProcessTerminated(Process process
) {
259 // If the child is already dead, then there's nothing to do.
260 if (IsChildDead(process
.Pid()))
263 const unsigned timeout
= 2; // seconds
264 BackgroundReaper
* reaper
= new BackgroundReaper(process
.Pid(), timeout
);
265 PlatformThread::CreateNonJoinable(0, reaper
);
268 void EnsureProcessGetsReaped(ProcessId pid
) {
269 // If the child is already dead, then there's nothing to do.
270 if (IsChildDead(pid
))
273 BackgroundReaper
* reaper
= new BackgroundReaper(pid
, 0);
274 PlatformThread::CreateNonJoinable(0, reaper
);
277 #endif // !defined(OS_MACOSX)
278 #endif // !defined(OS_NACL_NONSFI)