From 6e65b36973cf97e7fcfe4cc4f731e441bc2e69f4 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 6 Aug 2021 01:04:11 +0200 Subject: [PATCH] LibCore: Add Core::Process::spawn() This is a simple wrapper around posix_spawn() that will help us simplify a bunch of very verbose posix_spawn() invocations. This first version only supports the simplest case: executing an executable without passing arguments or doing anything fancy. More features can be added to cover more cases. :^) --- Userland/Libraries/LibCore/CMakeLists.txt | 1 + Userland/Libraries/LibCore/Process.cpp | 36 +++++++++++++++++++++++ Userland/Libraries/LibCore/Process.h | 18 ++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 Userland/Libraries/LibCore/Process.cpp create mode 100644 Userland/Libraries/LibCore/Process.h diff --git a/Userland/Libraries/LibCore/CMakeLists.txt b/Userland/Libraries/LibCore/CMakeLists.txt index adafbcc559..1bf5af2204 100644 --- a/Userland/Libraries/LibCore/CMakeLists.txt +++ b/Userland/Libraries/LibCore/CMakeLists.txt @@ -21,6 +21,7 @@ set(SOURCES NetworkResponse.cpp Notifier.cpp Object.cpp + Process.cpp ProcessStatisticsReader.cpp Property.cpp Socket.cpp diff --git a/Userland/Libraries/LibCore/Process.cpp b/Userland/Libraries/LibCore/Process.cpp new file mode 100644 index 0000000000..9d01b86306 --- /dev/null +++ b/Userland/Libraries/LibCore/Process.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021, Andreas Kling + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include +#include +#include +#include +#include + +#ifdef __serenity__ +# include +#endif + +namespace Core { + +pid_t Process::spawn(StringView path) +{ + String path_string = path; + + pid_t pid; + char const* argv[] = { path_string.characters(), nullptr }; + if ((errno = posix_spawn(&pid, path_string.characters(), nullptr, nullptr, const_cast(argv), environ))) { + perror("Process::spawn posix_spawn"); + } else { +#ifdef __serenity__ + if (disown(pid) < 0) + perror("Process::spawn disown"); +#endif + } + return pid; +} + +} diff --git a/Userland/Libraries/LibCore/Process.h b/Userland/Libraries/LibCore/Process.h new file mode 100644 index 0000000000..79820451e2 --- /dev/null +++ b/Userland/Libraries/LibCore/Process.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2021, Andreas Kling + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include + +namespace Core { + +class Process { +public: + static pid_t spawn(StringView path); +}; + +}