【发布时间】:2015-05-23 03:01:33
【问题描述】:
我正在尝试在 C 中执行相当于 bash 命令 ls>foo.txt 的操作。
下面的代码将输出重定向到一个变量。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
close(pfds[0]);
//close(1);//Close stdout
//dup(pfds[1]);
//execlp("ls", "ls", NULL);
write(pfds[1], "test", 5); //Writing in the pipe
exit(0);
} else {
close(pfds[1]);
read(pfds[0], buf, 5); //Read from pipe
wait(NULL);
}
return 0;
}
cmets 行指的是我认为重定向所需的那些操作。 我应该改变什么来将 ls 的输出重定向到 foo.txt?
【问题讨论】:
-
当你模拟的 shell 语法中没有显示管道时,为什么要创建管道?
-
“等效于 C 中的 [this bash code]”不会成为 bash 问题。如果您希望 bash(而不是 C!)方面的专家查看它,请仅将其标记为 bash。