Process.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  4. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/ByteString.h>
  10. #include <AK/Forward.h>
  11. #include <AK/Span.h>
  12. #include <LibCore/File.h>
  13. namespace Core {
  14. namespace FileAction {
  15. struct OpenFile {
  16. ByteString path;
  17. File::OpenMode mode = File::OpenMode::NotOpen;
  18. int fd = -1;
  19. mode_t permissions = 0600;
  20. };
  21. // FIXME: Implement other file actions
  22. }
  23. struct ProcessSpawnOptions {
  24. ByteString executable;
  25. bool search_for_executable_in_path { false };
  26. Vector<ByteString> const& arguments = {};
  27. Optional<ByteString> working_directory = {};
  28. Vector<Variant<FileAction::OpenFile>> const& file_actions = {};
  29. };
  30. class Process {
  31. AK_MAKE_NONCOPYABLE(Process);
  32. public:
  33. enum class KeepAsChild {
  34. Yes,
  35. No
  36. };
  37. Process(Process&& other)
  38. : m_pid(exchange(other.m_pid, 0))
  39. , m_should_disown(exchange(other.m_should_disown, false))
  40. {
  41. }
  42. Process& operator=(Process&& other) = delete;
  43. ~Process()
  44. {
  45. (void)disown();
  46. }
  47. static ErrorOr<Process> spawn(ProcessSpawnOptions const& options);
  48. // FIXME: Make the following 2 functions return Process instance or delete them.
  49. static ErrorOr<pid_t> spawn(StringView path, ReadonlySpan<ByteString> arguments, ByteString working_directory = {}, KeepAsChild keep_as_child = KeepAsChild::No);
  50. static ErrorOr<pid_t> spawn(StringView path, ReadonlySpan<StringView> arguments, ByteString working_directory = {}, KeepAsChild keep_as_child = KeepAsChild::No);
  51. // FIXME: Remove this. char const* should not exist on this level of abstraction.
  52. static ErrorOr<pid_t> spawn(StringView path, ReadonlySpan<char const*> arguments = {}, ByteString working_directory = {}, KeepAsChild keep_as_child = KeepAsChild::No);
  53. static ErrorOr<String> get_name();
  54. enum class SetThreadName {
  55. No,
  56. Yes,
  57. };
  58. static ErrorOr<void> set_name(StringView, SetThreadName = SetThreadName::No);
  59. static void wait_for_debugger_and_break();
  60. static ErrorOr<bool> is_being_debugged();
  61. pid_t pid() const { return m_pid; }
  62. ErrorOr<void> disown();
  63. // FIXME: Make it return an exit code.
  64. ErrorOr<bool> wait_for_termination();
  65. private:
  66. Process(pid_t pid)
  67. : m_pid(pid)
  68. , m_should_disown(true)
  69. {
  70. }
  71. pid_t m_pid;
  72. bool m_should_disown;
  73. };
  74. }