| 6 |
| 7 | #include "base/bind.h" |
| 8 | #include "base/process/process_iterator.h" |
| 9 | #include "base/task/post_task.h" |
| 10 | #include "base/task/thread_pool.h" |
| 11 | #include "base/time/time.h" |
| 12 |
| 13 | namespace base { |
| 14 |
| 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 defined(OS_WIN) || defined(OS_FUCHSIA) |
| 36 | // Common implementation for platforms under which |process| is a handle to |
| 37 | // the process, rather than an identifier that must be "reaped". |
| 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 defined(OS_WIN) |
| 52 | process.Terminate(win::kProcessKilledExitCode, false); |
| 53 | #else |
| 54 | process.Terminate(-1, false); |
| 55 | #endif |
| 56 | }, |
| 57 | std::move(process)), |
| 58 | TimeDelta::FromSeconds(2)); |
| 59 | } |
| 60 | #endif // defined(OS_WIN) || defined(OS_FUCHSIA) |
| 61 |
| 62 | } // namespace base |
| 63 |