UNIXworkcode

/* * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2016 Olaf Wintermann <olaf.wintermann@gmail.com> * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. */ /* * This program adds a log prefix to each stdout line */ #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; } // make fd 1(stdout) refer to the new pipe 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); }