[libc-commits] [libc] [llvm] [libc] implement popen/pclose (PR #232846)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Mon Oct 19 02:04:32 PDT 2026
================
@@ -0,0 +1,79 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Helpers for running a command with the shell in a child process, shared by
+/// functions like system and popen.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_OSUTIL_LINUX_SHELL_FORK_H
+#define LLVM_LIBC_SRC___SUPPORT_OSUTIL_LINUX_SHELL_FORK_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/signal_macros.h"
+#include "hdr/types/pid_t.h"
+#include "src/__support/CPP/functional.h"
+#include "src/__support/OSUtil/exit.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/clone3.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/execle.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/wait4.h"
+#include "src/__support/common.h"
+#include "src/__support/error_or.h"
+#include "src/__support/macros/config.h"
+#include "src/unistd/environ.h"
+
+#include <linux/sched.h> // For struct clone_args
+
+namespace LIBC_NAMESPACE_DECL {
+
+LIBC_INLINE_VAR constexpr char SHELL_PATH[] = "/bin/sh";
+
+// Work to do in the child process after forking and before executing the
+// shell. Returns false if the setup failed and the shell should not be run.
+using ShellChildSetup = cpp::function<bool()>;
+
+// Forks a child process which runs |setup| and then executes
+// "sh -c |command|" with the current environment. If |setup| or the exec
+// fails, the child exits with status 127. Returns the child's pid in the
+// parent.
+LIBC_INLINE ErrorOr<pid_t> shell_fork(const char *command,
+ ShellChildSetup setup) {
+ struct clone_args cl_args{};
+ cl_args.exit_signal = SIGCHLD;
+ ErrorOr<pid_t> fork_res = linux_syscalls::clone3(&cl_args, sizeof(cl_args));
+ if (!fork_res.has_value())
+ return Error(fork_res.error());
+
+ if (fork_res.value() == 0) {
+ // Error checking isn't helpful since this is the forked process, so we
+ // can't set errno. All we can meaningfully do is exit with status 127.
+ if (setup())
+ linux_syscalls::execle(SHELL_PATH, "sh", "-c", command, 0, environ);
----------------
labath wrote:
POSIX says this should include "--". It matters when command starts with a '-'.
```suggestion
linux_syscalls::execle(SHELL_PATH, "sh", "-c", "--", command, 0, environ);
```
https://github.com/llvm/llvm-project/pull/232846
More information about the libc-commits
mailing list