C还原标准输出到终端 [英] C restore stdout to terminal

查看:130
本文介绍了C还原标准输出到终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是多线程程序的工作。

首先,我重定向我的标准输出到某个文件。这里没有问题(我用 dup2(FD,1),其中 FD 是文件的文件描述符)。

之后,我需要我的标准输出重定向再次到终端。

我的第一种方法:

  / * *声明/
      fpost_t stream_sdout;
      / * code * /
      如果(fgetpos(标准输出,和放大器; stream_sdout)== -1)
          PERROR(错误:);

我说ilegal求。
不知道为什么会这样。
但是,如果我得到这个工作,那么我只需要使用 fsetpos(标准输出,和放大器; stream_stdout),它应该工作。

我的第二个想法,就是利用复制的标准输出 dup2(标准输出,4)来文件描述符表,位置4.但是,这不工作要么

如何切换到标准输出回原来的目的地(终端,管道,文件,等等)?


解决方案

 的#include<&unistd.h中GT;...INT saved_stdout;.../ *后保存使用当前的标准输出* /
saved_stdout = DUP(1);
dup2(my_temporary_stdout_fd,1);......做你的新标准输出一些工作.../ *恢复标准输出* /
dup2(saved_stdout,1);
关闭(saved_stdout);

I am working with a multi-thread program.

First I redirect my stdout to a certain file. No problem there (I used dup2(fd, 1) where fd is the file descriptor for the file).

Afterwards, I need to redirect my stdout to the terminal again.

My first approach:

      /*Declaration*/
      fpost_t  stream_sdout;
      /*code*/
      if ( fgetpos( stdout, &stream_sdout) == -1 )
          perror(Error:);

I says ilegal seek. No idea why this is happening. But if I get this to work, then I only need to use fsetpos(stdout, &stream_stdout) and it should work.

My second idea, was to to copy the stdout using dup2(stdout, 4) to the file descriptor table, at position 4. But that ain't working either.

How can I switch the standard output back to its original destination (terminal, pipe, file, whatever)?

解决方案

#include <unistd.h>

...

int saved_stdout;

...

/* Save current stdout for use later */
saved_stdout = dup(1);
dup2(my_temporary_stdout_fd, 1);

... do some work on your new stdout ...

/* Restore stdout */
dup2(saved_stdout, 1);
close(saved_stdout);

这篇关于C还原标准输出到终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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