xref: /aosp_15_r20/external/cronet/base/process/kill.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
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/functional/bind.h"
8 #include "base/process/process_iterator.h"
9 #include "base/task/thread_pool.h"
10 #include "base/time/time.h"
11 #include "build/build_config.h"
12 
13 namespace base {
14 
KillProcesses(const FilePath::StringType & executable_name,int exit_code,const ProcessFilter * filter)15 bool KillProcesses(const FilePath::StringType& executable_name,
16                    int exit_code,
17                    const ProcessFilter* filter) {
18   bool result = true;
19   NamedProcessIterator iter(executable_name, filter);
20   while (const ProcessEntry* entry = iter.NextProcessEntry()) {
21     Process process = Process::Open(entry->pid());
22     // Sometimes process open fails. This would cause a DCHECK in
23     // process.Terminate(). Maybe the process has killed itself between the
24     // time the process list was enumerated and the time we try to open the
25     // process?
26     if (!process.IsValid()) {
27       result = false;
28       continue;
29     }
30     result &= process.Terminate(exit_code, true);
31   }
32   return result;
33 }
34 
35 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
36 // Common implementation for platforms under which |process| is a handle to
37 // the process, rather than an identifier that must be "reaped".
EnsureProcessTerminated(Process process)38 void EnsureProcessTerminated(Process process) {
39   DCHECK(!process.is_current());
40 
41   if (process.WaitForExitWithTimeout(TimeDelta(), nullptr))
42     return;
43 
44   ThreadPool::PostDelayedTask(
45       FROM_HERE,
46       {TaskPriority::BEST_EFFORT, TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
47       BindOnce(
48           [](Process process) {
49             if (process.WaitForExitWithTimeout(TimeDelta(), nullptr))
50               return;
51 #if BUILDFLAG(IS_WIN)
52             process.Terminate(win::kProcessKilledExitCode, false);
53 #else
54             process.Terminate(-1, false);
55 #endif
56           },
57           std::move(process)),
58       Seconds(2));
59 }
60 #endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
61 
62 }  // namespace base
63