重定向 I/O,在 C 中实现 shell [英] redirecting I/O, implementation of a shell in C

查看:25
本文介绍了重定向 I/O,在 C 中实现 shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个 shell,在我的 shell 中,我必须能够处理 '>' '<''>>' '|'.我的大部分工作都完成了,但是当用户想要在命令行中输入以下内容时:

I'm implementing a shell, and in my shell i have to be able to process '>' '<' '>>' '|'. I got most of it working, but when the user wants to input in the command line something like:

SHELL$ sort < input > output

我没有得到确切的结果.我得到的是排序将输出发送到 STDOUT,然后对来自 STDIN 的读取进行排序并将输出发送到输出"

im not getting the exact result. What I get is sort sending the output to STDOUT, and then sort reading from STDIN and sending the output to "output"

我知道我必须使用

dup2(fd, STDIN_FILENO)

fd 是输入文件的文件描述符.

fd being the file descriptor of the input file.

我好奇的部分是如何重定向排序的输出,而不是将输出发送到 STDOUT,而是将其发送到 w.e '>' 所指向的,在我的示例中是输出

The part im curious about is how can i redirect the output of sort, instead of sending the output to STDOUT, sending it to w.e '>' is pointing to, which in my example is output

所以命令 sort 读取 input: " sort < input " 和 this: " > output " 最终将 sort 的输出发送到 "output".

So the command sort reads input: " sort < input " and this: " > output " will eventually send the output of sort to "output".

提前致谢!

推荐答案

in = open("input",O_RDONLY);
dup2(in,STDIN_FILENO);
close(in);
out = open("output",O_WRONLY|O_CREAT,0666); // Should also be symbolic values for access rights
dup2(out,STDOUT_FILENO);
close(out);
execlp("sort","sort",NULL);

这篇关于重定向 I/O,在 C 中实现 shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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