【问题标题】:Using Dup2 to Redirect Input and Output [duplicate]使用 Dup2 重定向输入和输出
【发布时间】:2013-07-08 01:24:21
【问题描述】:

我一直在用 C 编写一个 Unix shell,我正在尝试实现输入和输出重定向。我一直在使用 Dup2 并且能够做到这一点,因此我的输出重定向到一个文件,并且我的输入也被正确重定向。但是,在我完成之后,如何再次使用 Stdin 和 Stdout?

这些是我在需要重定向时运行的代码:

在:

inFile = open(tok.infile, O_RDONLY, 0);
inDup = dup2(inFile, STDIN_FILENO);
close(inFile);

输出:

outFile = creat(tok.outfile, 0644);
outDup = dup2(outFile, STDOUT_FILENO);
close(outFile);

【问题讨论】:

  • 我觉得你应该重新试验一下,看看,如果你没有关闭它们,我会尝试将它们复制到0和1。

标签: c dup2


【解决方案1】:
int stdinHolder = dup(0);
int stdoutHolder = dup(1);
close(0);
close(1);

然后在你完成后你可以复制回标准输入和标准输出的持有者。

int stdinHolder = dup(1);
int stdoutHolder = dup(0);
close(0);
close(1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多