简体   繁体   English

shell c中的输入输出重定向

[英]input output redirection in shell c

I implement a simple shell. 我实现了一个简单的外壳。 I want to use input/ output redirection. 我想使用输入/输出重定向。 I write some piece of code but my code doesn't work. 我写了一些代码,但是我的代码不起作用。 here is my code : 这是我的代码:

You're duplicating the FD into FD 0, which is stdin . 您正在将FD复制到FD 0,即stdin stdout is FD 1. You should also use dup2 , so you can specify explicitly which FD to assign to, and the macro that holds the FD. stdout是FD1。您还应该使用dup2 ,以便可以明确指定要分配给哪个FD,以及保存该FD的宏。

dup2(fd, STDOUT_FILENO);

You should also change 你也应该改变

if (*args[i] == '>')

to

if (strcmp(args[i], ">") == 0)

Otherwise it matches any argument that begins with > , even if it has other characters after it. 否则,它将匹配任何以>开头的参数,即使它后面还有其他字符也是如此。

(get used writing %s\\n in your printf statements) (在printf语句中习惯于写%s\\n

When your compiled program is called myshell, you will see the > when it is given as an argument: 当您将编译后的程序称为myshell时,在将其作为参数给出时,您会看到>:

./myshell arg1 arg2 ">" arg4

When you don't quote the > , the shell will take care of the redirection: 当您不引用> ,shell将负责重定向:

# Not what you want:
./myshell arg1 arg2 > arg4

would result in myshell being called with parameters arg1 and arg2, and the result of myshell will be redirected to arg4. 将导致使用参数arg1和arg2调用myshell,并将myshell的结果重定向到arg4。

i think that u do not need asterisk* in your If condition. 我认为您的If条件中不需要星号*。 You want to to compare value of args[x] with a sign '>'. 您想将args [x]的值与符号“>”进行比较。

In case it's not it, Can you write little more about the error which occurs? 如果不是,您能否再多写一些有关发生的错误的信息?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM