Skip to content

Commit 14e926a

Browse files
committed
refactor: extract MakeArgv helper
The next commit will use it to create an alternative to ExecProcess that's safe to call post-fork. Added a note that ExecProcess is not safe to call post-fork. Since it's only used by mpgen at build time, this is fine, and lets of print useful errors.
1 parent 470fc51 commit 14e926a

2 files changed

Lines changed: 14 additions & 6 deletions

File tree

include/mp/util.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,8 @@ using FdToArgsFn = std::function<std::vector<std::string>(int fd)>;
228228
int SpawnProcess(int& pid, FdToArgsFn&& fd_to_args);
229229

230230
//! Call execvp with vector args.
231+
//! Not safe to call in a post-fork child of a multi-threaded process.
232+
//! Currently only used by mpgen at build time.
231233
void ExecProcess(const std::vector<std::string>& args);
232234

233235
//! Wait for a process to exit and return its exit code.

src/mp/util.cpp

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,17 @@ namespace fs = std::filesystem;
3636
namespace mp {
3737
namespace {
3838

39+
std::vector<char*> MakeArgv(const std::vector<std::string>& args)
40+
{
41+
std::vector<char*> argv;
42+
argv.reserve(args.size() + 1);
43+
for (const auto& arg : args) {
44+
argv.push_back(const_cast<char*>(arg.c_str()));
45+
}
46+
argv.push_back(nullptr);
47+
return argv;
48+
}
49+
3950
//! Return highest possible file descriptor.
4051
size_t MaxFd()
4152
{
@@ -134,12 +145,7 @@ int SpawnProcess(int& pid, FdToArgsFn&& fd_to_args)
134145

135146
void ExecProcess(const std::vector<std::string>& args)
136147
{
137-
std::vector<char*> argv;
138-
argv.reserve(args.size());
139-
for (const auto& arg : args) {
140-
argv.push_back(const_cast<char*>(arg.c_str()));
141-
}
142-
argv.push_back(nullptr);
148+
const std::vector<char*> argv{MakeArgv(args)};
143149
if (execvp(argv[0], argv.data()) != 0) {
144150
perror("execvp failed");
145151
if (errno == ENOENT && !args.empty()) {

0 commit comments

Comments
 (0)