linux - 将输出重定向到 C 中的文件

标签 linux shell

我用 C 语言编写了一个基本的 shell 来执行基本命令,它将执行命令 ls, ls -al , ls -al |更多

我想在我的 shell 中执行以下命令。 喜欢;

ls -al > a.txt

这将给我 a.txt 文件,其中包含 ls -al 过程的输出。 我找到了一个解决方案,它正在更改我的 shell 中的命令,如 [command1] | tee [文件名]。在这种情况下,它会将 ls -al > a.txt 更改为 ls -al | tee a.txt.但是这个过程也将输出提供给文件和终端。如何在终端中停止打印输出。

或者是否有比使用 tee 命令更好的解决方案。 提前致谢...

最佳答案

这是我用 dup2 测试的结果

更微妙的一点是在正确的时间记住 fflush :) 否则,你会得到非常令人惊讶的结果。

此外,首选 fileno 而不是硬编码 1 (stdout) 2 (stderr)。

重定向 stdin 留给读者作为练习

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
    int out = open("cout.log", O_RDWR|O_CREAT|O_APPEND, 0600);
    if (-1 == out) { perror("opening cout.log"); return 255; }

    int err = open("cerr.log", O_RDWR|O_CREAT|O_APPEND, 0600);
    if (-1 == err) { perror("opening cerr.log"); return 255; }

    int save_out = dup(fileno(stdout));
    int save_err = dup(fileno(stderr));

    if (-1 == dup2(out, fileno(stdout))) { perror("cannot redirect stdout"); return 255; }
    if (-1 == dup2(err, fileno(stderr))) { perror("cannot redirect stderr"); return 255; }

    puts("doing an ls or something now");

    fflush(stdout); close(out);
    fflush(stderr); close(err);

    dup2(save_out, fileno(stdout));
    dup2(save_err, fileno(stderr));

    close(save_out);
    close(save_err);

    puts("back to normal output");

    return 0;
}

关于linux - 将输出重定向到 C 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8516823/

相关文章:

c - 使用 fgets 读取输入在 C 中返回重复行

linux - 如何使用 ansible 运行需要中断操作的 shell 文件

linux - 自定义 bash_profile 中的 git 命令以自动索引到下一个分支

linux - 设置挂起超时跨窗口管理器

c - 如何链接内核模块来使用它们的功能?

shell - 在 Tcl 中执行管道 shell 命令

shell - 使用 find 和 xargs 以交互方式删除文件

linux - zsh 中的退格键无法以非常奇怪的方式工作

linux - Bash - 在一个命令中杀死所有进程

c - 动态添加条目到 sysctl