-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonExecutor.cpp
More file actions
71 lines (65 loc) · 2.72 KB
/
Copy pathPythonExecutor.cpp
File metadata and controls
71 lines (65 loc) · 2.72 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
/**
* @file
* Copyright (c) 2023 - Tidaly
* Authors:
* - Philippe CHEYPE <philippe.cheype@epitech.eu>
* - Quentin ROUVIER <quentin.rouvier@epitech.eu>
* NOTICE: All information contained herein is, and remains
* the property of Tidaly. Dissemination of this information
* or reproduction of this material is strictly forbidden
* unless prior written permission is obtained from Tidaly.
*/
#include "Core/PythonExecutor/PythonExecutor.hpp"
std::string const PyExecutor::executeScript(std::string const& scriptPath, std::string const& imagePath, int lastValue) {
int pipefd[2];
// if (pipe(pipefd) == -1) {
// THROW_EXCEPTION(PythonExecutorError, "Failed to create the pipe.");
// }
pid_t pid = fork();
// if (pid == -1) {
// THROW_EXCEPTION(PythonExecutorError, "Failed to fork the process.");
// }
if (pid == 0) {
// Child process
close(pipefd[0]);
// if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
// THROW_EXCEPTION(PythonExecutorError, "Failed to redirect stdout.");
// }
signal(SIGALRM, [](int) { exit(1); });
alarm(60); // 60 seconds timeout
execlp("python3", "python3", scriptPath.c_str(), imagePath.c_str(), std::to_string(lastValue).c_str(), nullptr);
// THROW_EXCEPTION(PythonExecutorError, "Failed to execute the python script.");
return "";
} else {
// Parent process
close(pipefd[1]);
std::array<char, 128> buffer;
std::string result;
while (read(pipefd[0], buffer.data(), buffer.size()) > 0) {
result += buffer.data();
}
int status;
waitpid(pid, &status, 0);
this->_handleExitStatus(status);
return result;
}
}
void PyExecutor::_handleExitStatus(int returnCode) {
if (returnCode != 0) {
if (WIFEXITED(returnCode)) {
int statusCode = WEXITSTATUS(returnCode);
std::cerr << "Command exited with status " << statusCode << std::endl;
THROW_EXCEPTION(PythonExecutorError, "Command execution failed with status code.");
// } else if (WIFSIGNALED(returnCode)) {
// int signalNumber = WTERMSIG(returnCode);
// if (signalNumber == SIGALRM) {
// throw std::runtime_error("PythonExecutor: Command execution timed out.");
// }
// std::cerr << "Command terminated by signal " << signalNumber << std::endl;
// THROW_EXCEPTION(PythonExecutorError, "Command terminated unexpectedly by a signal.");
// } else {
// std::cerr << "Command failed with return code " << returnCode << std::endl;
// THROW_EXCEPTION(PythonExecutorError, "Command execution failed.");
}
}
}