• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "base/process/kill.h"
6 
7 #include "base/bind.h"
8 #include "base/process/process_iterator.h"
9 #include "base/task_scheduler/post_task.h"
10 #include "base/time/time.h"
11 
12 namespace base {
13 
KillProcesses(const FilePath::StringType & executable_name,int exit_code,const ProcessFilter * filter)14 bool KillProcesses(const FilePath::StringType& executable_name,
15                    int exit_code,
16                    const ProcessFilter* filter) {
17   bool result = true;
18   NamedProcessIterator iter(executable_name, filter);
19   while (const ProcessEntry* entry = iter.NextProcessEntry()) {
20     Process process = Process::Open(entry->pid());
21     // Sometimes process open fails. This would cause a DCHECK in
22     // process.Terminate(). Maybe the process has killed itself between the
23     // time the process list was enumerated and the time we try to open the
24     // process?
25     if (!process.IsValid()) {
26       result = false;
27       continue;
28     }
29     result &= process.Terminate(exit_code, true);
30   }
31   return result;
32 }
33 
34 #if defined(OS_WIN) || defined(OS_FUCHSIA)
35 // Common implementation for platforms under which |process| is a handle to
36 // the process, rather than an identifier that must be "reaped".
EnsureProcessTerminated(Process process)37 void EnsureProcessTerminated(Process process) {
38   DCHECK(!process.is_current());
39 
40   if (process.WaitForExitWithTimeout(TimeDelta(), nullptr))
41     return;
42 
43   PostDelayedTaskWithTraits(
44       FROM_HERE,
45       {TaskPriority::BACKGROUND, TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
46       BindOnce(
47           [](Process process) {
48             if (process.WaitForExitWithTimeout(TimeDelta(), nullptr))
49               return;
50 #if defined(OS_WIN)
51             process.Terminate(win::kProcessKilledExitCode, false);
52 #else
53             process.Terminate(-1, false);
54 #endif
55           },
56           std::move(process)),
57       TimeDelta::FromSeconds(2));
58 }
59 #endif  // defined(OS_WIN) || defined(OS_FUCHSIA)
60 
61 }  // namespace base
62