我用 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/