Repository navigation
Expand file tree
/
Copy pathbackground.cpp
More file actions
101 lines (89 loc) · 2.55 KB
/
Copy pathbackground.cpp
File metadata and controls
101 lines (89 loc) · 2.55 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "headers.h"
// PIDs of jobs started with a trailing '&'. Reaped in reapBackgroundProcesses().
static vector<pid_t> backgroundPids;
static char **buildArgv(const vector<string> &args)
{
char **argv = new char *[args.size() + 1];
for (size_t i = 0; i < args.size(); ++i)
{
argv[i] = new char[args[i].size() + 1];
strcpy(argv[i], args[i].c_str());
}
argv[args.size()] = nullptr;
return argv;
}
void executeBackgroundProcess(vector<string> args, bool runInBackground, int &foregroundJobPid, bool &foregroundJobRunning)
{
if (args.empty())
return;
pid_t pid = fork();
if (pid == 0)
{
// Child: restore default signal handling before exec.
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
if (runInBackground)
{
// Detach from the terminal so background jobs don't steal input
// or get killed by Ctrl-C/Ctrl-Z aimed at the shell.
setpgid(0, 0);
}
char **argv = buildArgv(args);
execvp(argv[0], argv);
cerr << args[0] << ": command not found" << endl;
_exit(127);
}
else if (pid > 0)
{
if (!runInBackground)
{
foregroundJobPid = pid;
foregroundJobRunning = true;
int status = 0;
while (waitpid(pid, &status, WUNTRACED) == -1 && errno == EINTR)
;
foregroundJobRunning = false;
foregroundJobPid = 0;
if (WIFSTOPPED(status))
{
backgroundPids.push_back(pid);
cout << "[stopped] " << pid << " " << args[0] << endl;
}
}
else
{
backgroundPids.push_back(pid);
cout << "[bg] " << pid << endl;
}
}
else
{
perror("fork");
}
}
void reapBackgroundProcesses(int signum)
{
(void)signum;
for (size_t i = 0; i < backgroundPids.size();)
{
int status = 0;
pid_t result = waitpid(backgroundPids[i], &status, WNOHANG | WUNTRACED | WCONTINUED);
if (result == 0)
{
++i; // still running
}
else if (result == -1)
{
backgroundPids.erase(backgroundPids.begin() + i); // already gone
}
else if (WIFEXITED(status) || WIFSIGNALED(status))
{
cout << backgroundPids[i] << " done" << endl;
backgroundPids.erase(backgroundPids.begin() + i);
}
else
{
++i; // stopped/continued: keep tracking
}
}
}