Skip to content

Commit 27f8b36

Browse files
committed
use file set per thread when redirecting stderr/out
1 parent 4efdb90 commit 27f8b36

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

src/fd.c

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
/// @brief File descriptor output redirection implementation.
33
#include "fd.h"
44

5+
#include <assert.h>
56
#include <errno.h>
67
#include <fcntl.h>
78
#include <stdio.h>
@@ -28,6 +29,17 @@ static int openfd(const char* name, const unsigned int id) {
2829
return fno;
2930
}
3031

32+
/// @brief Closes the file descriptor if open (indicated by a value of >=0) and
33+
/// sets it to -1.
34+
/// @param fd Pointer to the file descriptor to close, must not be NULL.
35+
static void closefd(int* fd) {
36+
assert(fd != NULL);
37+
if (*fd >= 0) {
38+
close(*fd);
39+
*fd = -1;
40+
}
41+
}
42+
3143
int fdinit(struct fdset_s* fds, const unsigned int id) {
3244
fds->out = fds->err = -1;
3345
if ((fds->out = openfd("stdout", id)) < 0) return -1;
@@ -39,12 +51,6 @@ int fdinit(struct fdset_s* fds, const unsigned int id) {
3951
}
4052

4153
void fdclose(struct fdset_s* fds) {
42-
if (fds->out >= 0) {
43-
close(fds->out);
44-
fds->out = -1;
45-
}
46-
if (fds->err >= 0) {
47-
close(fds->err);
48-
fds->err = -1;
49-
}
54+
closefd(&fds->out);
55+
closefd(&fds->err);
5056
}

src/tp.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,12 @@ static void* tpentrypoint(void* arg) {
6969
/// file descriptor set initialization fails, or the flag is not set, the file
7070
/// descriptors will default to \p STDOUT_FILENO and \p STDERR_FILENO.
7171
/// @param t The thread to configure
72+
/// @param uid The thread pool thread ID for logging
7273
/// @param flags The configuration flags
73-
static void tpinitthrd(struct thrd_s* t, const int flags) {
74+
static void tpinitthrd(struct thrd_s* t, const int uid, const int flags) {
7475
int err;
7576
if (flags & TPOPT_LOGFILES) {
76-
if ((err = fdinit(&t->fds, 0))) {
77+
if ((err = fdinit(&t->fds, uid))) {
7778
log_error("file descriptor set open error: %d", err);
7879
} else {
7980
t->fdsopen = true;
@@ -94,7 +95,7 @@ int tpinit(const int size, const int flags) {
9495
for (int i = 0; i < size; i++) {
9596
if ((thrds[i] = calloc(1, sizeof(struct thrd_s))) == NULL) goto fail;
9697
struct thrd_s* t = thrds[i];
97-
tpinitthrd(t, flags);
98+
tpinitthrd(t, i, flags);
9899
int err;
99100
if ((err = pthread_create(&t->tid, NULL, tpentrypoint, t))) {
100101
log_error("cannot create thread: %s", strerror(err));

0 commit comments

Comments
 (0)