Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

redirecting I/O, implementation of a shell in C

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

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"

I know i have to redirect the input of sort using

dup2(fd, STDIN_FILENO)

fd being the file descriptor of the input file.

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

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

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...