-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.cpp
More file actions
51 lines (43 loc) · 930 Bytes
/
process.cpp
File metadata and controls
51 lines (43 loc) · 930 Bytes
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
#include "allFunctions.h"
extern pid_t pid;
// Forks and executes an external command with optional background execution
void startProcess(vector<string> &args)
{
if (args.empty())
return;
bool bg = false;
if (args.back() == "&")
{
bg = true;
args.pop_back();
}
vector<char *> arr;
for (int i = 0; i < args.size(); i++)
arr.push_back((char *)args[i].c_str());
arr.push_back(nullptr);
pid = fork();
if (pid < 0)
{
perror("fork failed");
return;
}
if (pid == 0)
{
if (execvp(arr[0], arr.data()) < 0)
{
cout << arr[0] << ": command not found" << endl;
}
}
else
{
if (bg)
{
cout << "Started background process PID: " << pid << endl;
}
else
{
int status;
waitpid(pid, &status, 0);
}
}
}