我如何能实现编程的C'三通'? [英] How can I implement 'tee' programmatically in C?

查看:157
本文介绍了我如何能实现编程的C'三通'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在C以编程方式(即不使用重定向命令行)实现三通的功能,例如,我的标准输出去stdout和日志文件。这需要对我的code和所有链接库,输出到标准输出这两种工作。没有办法做到这一点?

I'm looking for a way in C to programmatically (ie, not using redirection from the command line) implement 'tee' functionality such that my stdout goes to both stdout and a log file. This needs to work for both my code and all linked libraries that output to stdout. Any way to do this?

推荐答案

您可以的popen()发球程序。

或者你可以叉()和管道标准输出通过一个子进程,如本(改编自一个真实的直播节目我写的,所以它的工作原理):

Or you can fork() and pipe stdout through a child process such as this (adapted from a real live program I wrote, so it works!):

void tee(const char* fname) {
    int pipe_fd[2];
    check(pipe(pipe_fd));
    const pid_t pid = fork();
    check(pid);
    if(!pid) { // our log child
    	close(pipe_fd[1]); // Close unused write end
    	FILE* logFile = fname? fopen(fname,"a"): NULL;
    	if(fname && !logFile)
    		fprintf(stderr,"cannot open log file \"%s\": %d (%s)\n",fname,errno,strerror(errno));
    	char ch;
    	while(read(pipe_fd[0],&ch,1) > 0) {
    		//### any timestamp logic or whatever here
    		putchar(ch);
    		if(logFile)
    			fputc(ch,logFile);
    		if('\n'==ch) {
    			fflush(stdout);
    			if(logFile)
    				fflush(logFile);
    		}
    	}
    	putchar('\n');
    	close(pipe_fd[0]);
    	if(logFile)
    		fclose(logFile);
    	exit(EXIT_SUCCESS);
    } else {
    	close(pipe_fd[0]); // Close unused read end
    	// redirect stdout and stderr
    	dup2(pipe_fd[1],STDOUT_FILENO);  
    	dup2(pipe_fd[1],STDERR_FILENO);  
    	close(pipe_fd[1]);  
    }
}

这篇关于我如何能实现编程的C'三通'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆