test: fix resource leak by closing pipe file descriptors in StreamCapture

Ensure all pipe file descriptors (FDs) are close

Add destructor and set descriptors to -1 after closing
to prevent double close.

Signed-off-by: Marcel Skierkowski <marcel.skierkowski@intel.com>
This commit is contained in:
Marcel Skierkowski
2025-07-04 12:59:33 +00:00
committed by Compute-Runtime-Automation
parent 509cc066e0
commit d896d98a61

View File

@@ -22,6 +22,19 @@
class StreamCapture {
public:
~StreamCapture() {
#ifdef _WIN32
if (pipefdStdout[0] != -1)
_close(pipefdStdout[0]);
if (pipefdStderr[0] != -1)
_close(pipefdStderr[0]);
#else
if (pipefdStdout[0] != -1)
close(pipefdStdout[0]);
if (pipefdStderr[0] != -1)
close(pipefdStderr[0]);
#endif
}
void captureStdout() {
captureStream(stdout, pipefdStdout, saveStdout);
}
@@ -46,6 +59,7 @@ class StreamCapture {
savedFd = _dup(_fileno(stream));
_dup2(pipefd[1], _fileno(stream));
_close(pipefd[1]);
pipefd[1] = -1;
#else
fflush(stream);
pipe(pipefd);
@@ -53,6 +67,7 @@ class StreamCapture {
savedFd = dup(fileno(stream));
dup2(pipefd[1], fileno(stream));
close(pipefd[1]);
pipefd[1] = -1;
#endif
}
@@ -64,6 +79,8 @@ class StreamCapture {
char buffer[bufferSize];
int count = _read(pipefd[0], buffer, sizeof(buffer) - 1);
_close(pipefd[0]);
pipefd[0] = -1;
if (count > 0) {
buffer[count] = '\0';
return std::string(buffer);
@@ -76,6 +93,8 @@ class StreamCapture {
char buffer[bufferSize];
ssize_t count = read(pipefd[0], buffer, bufferSize - 1);
close(pipefd[0]);
pipefd[0] = -1;
if (count > 0) {
buffer[count] = '\0';
return std::string(buffer);
@@ -84,8 +103,8 @@ class StreamCapture {
#endif
}
static constexpr size_t bufferSize = 16384;
int pipefdStdout[2];
int pipefdStderr[2];
int saveStdout;
int saveStderr;
int pipefdStdout[2]{-1, -1};
int pipefdStderr[2]{-1, -1};
int saveStdout{-1};
int saveStderr{-1};
};