如何从打印prevent功能? [英] How to prevent function from printing?

查看:150
本文介绍了如何从打印prevent功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能的沉默的功能?
例如:

Is it possible to silence a function? For example:

#include <stdio.h>
int function(){
  printf("BLAH!");
  return 10;

}
int main(){
  printf("%d", silence( function()) );
return 0;
}

而不是和:

BLAH!
10

我会得到:

10

这可能吗?如果正怎么办呢?

Is it possible? If positive how to do it?

推荐答案

这是非常复杂的方式做几乎你想要的是使用的 dup2()系统调用。这就要求执行 fflush(标准输出); dup2(silentfd,标准输出); 函数()被调用,复制回来算账: fflush(标准输出); dup2(savedstdoutfd,标准输出); 。所以这是不可能做到的只是沉默(函数()),因为这个构造只允许在执行code函数() 已经执行。

An awfully complicated way to do almost what you want is to use the dup2() system call. This requires executing fflush(stdout); dup2(silentfd, stdout); before function() is called, and copying back afterwards: fflush(stdout); dup2(savedstdoutfd, stdout);. So it is not possible to do as just silence(function()), since this construct only allows to execute code after function() has already been executed.

文件描述符 silentfd savedstdoutfd 必须是$ P $提前ppared(未经测试code ):

The file descriptors silentfd and savedstdoutfd have to be prepared in advance (untested code):

 int silentfd = open("/dev/null",O_WRONLY);
 int savedstdoutfd = dup(stdout);

这是几乎可以肯定不是你真正想要的,但因为你的问题被表述为这可能吗?,答案是差不多。

This is almost certainly not what you really want, but inasmuch as your question is phrased as "is it possible?", the answer is "almost".

这篇关于如何从打印prevent功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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