-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.cpp
More file actions
73 lines (60 loc) · 1.61 KB
/
Copy paththread.cpp
File metadata and controls
73 lines (60 loc) · 1.61 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
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <chrono>
#include <thread>
#include <csignal>
const std::string PYTHON_SCRIPT = "test2.py";
const int RUN_DURATION_SEC = 25;
int main()
{
int sessionCount = 1;
bool jobFinished = false;
while (!jobFinished)
{
pid_t pid = fork();
if (pid < 0)
{
std::cerr << "Fork failed.\n";
return 1;
}
else if (pid == 0)
{
execlp("python3", "python3", PYTHON_SCRIPT.c_str(), (char *)NULL);
std::cerr << "Failed to execute.\n";
exit(1);
}
else
{
bool childExitedEarly = false;
int status;
for (int i = 0; i < RUN_DURATION_SEC; ++i)
{
pid_t result = waitpid(pid, &status, WNOHANG);
if (result == pid)
{
childExitedEarly = true;
break;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if (childExitedEarly)
{
if (!(WIFEXITED(status) && WEXITSTATUS(status) == 0))
{
std::cerr << "Job finished with errors.\n";
}
jobFinished = true;
}
else
{
kill(pid, SIGTERM);
waitpid(pid, &status, 0);
std::this_thread::sleep_for(std::chrono::seconds(2));
sessionCount++;
}
}
}
return 0;
}