kill.cc 2.0 KB

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