-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathProcess_UNIX.cpp
More file actions
76 lines (65 loc) · 1.74 KB
/
Copy pathProcess_UNIX.cpp
File metadata and controls
76 lines (65 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "hacklib/Process.h"
#include <stdexcept>
#include <cstring>
#include <cstdio>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int hl::Process::join()
{
(void)m_handle;
if (!m_id)
{
throw std::runtime_error("Process is not joinable");
}
int status, result;
do
{
result = waitpid(m_id, &status, 0);
} while (result < 0 && errno == EINTR);
if (result != m_id)
{
throw std::runtime_error("waitpid failed");
}
m_id = 0;
if (WIFEXITED(status))
return WEXITSTATUS(status);
else if (WIFSIGNALED(status))
return -WTERMSIG(status);
else
return -1;
}
hl::Process hl::LaunchProcess(const std::string& command, const std::vector<std::string>& args,
const std::string& initialDirectory)
{
std::vector<char*> argv;
argv.push_back(const_cast<char*>(command.c_str()));
for (const auto& arg : args)
{
argv.push_back(const_cast<char*>(arg.c_str()));
}
argv.push_back(nullptr);
const char* initialDirectoryCStr = initialDirectory.empty() ? NULL : initialDirectory.c_str();
int pid = fork();
if (pid < 0)
{
throw std::runtime_error("fork failed");
}
else if (pid == 0)
{
if (initialDirectoryCStr)
{
if (chdir(initialDirectoryCStr) != 0)
{
printf("chdir failed: %s\n", strerror(errno));
_exit(72);
}
}
execvp(argv[0], argv.data());
// Will only reach here on error.
// Call special exit to prevent parent process doing double cleanup.
printf("execvp failed: %s\n", strerror(errno));
_exit(72);
}
return Process(pid, 0);
}