#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
static int std_out_fd;
static int pipe_fds[2];
void* pipe_filter_thread(void *data) {
FILE *std_out = fdopen(std_out_fd, "w");
if(!std_out) {
return NULL;
}
FILE *pipe = fdopen(pipe_fds[0], "r");
if(!pipe) {
fclose(std_out);
return NULL;
}
int newline = 1;
int c;
while((c = fgetc(pipe)) != EOF) {
if(newline) {
char datebuf[64];
struct tm* tm;
time_t t;
time(&t);
tm = localtime(&t);
size_t len = strftime(datebuf, 64, "%Y-%m-%d %H:%M:%S stdout: ", tm);
fwrite(datebuf, 1, len, std_out);
newline = 0;
}
fputc(c, std_out);
if(c == '\n') {
newline = 1;
fflush(std_out);
}
}
fclose(std_out);
fclose(pipe);
return NULL;
}
int main(int argc, char** argv) {
std_out_fd = dup(STDOUT_FILENO);
if(pipe(pipe_fds) != 0) {
perror("pipe");
return EXIT_FAILURE;
}
dup2(pipe_fds[1], STDOUT_FILENO);
close(pipe_fds[1]);
pthread_t tid;
if(pthread_create(&tid, NULL, pipe_filter_thread, NULL) != 0) {
perror("pthread_create");
return EXIT_FAILURE;
}
printf("Hello World!\n");
printf("some text\nanother line\n");
fclose(stdout);
pthread_join(tid, NULL);
return (EXIT_SUCCESS);
}