[英]Redirecting input and output in a shell
嗨,我一直在用c编写shell,尝试重定向时被卡住了。 在我的程序中重定向标准输出时,标准输入不起作用。
void redirect(node_t* node){
// mode 0: >$%d mode 1: < mode 2: > mode 3: >>
int input = 0;
if(node->redirect.mode == 2){
input = 1; // >
} else{
input = 0; // <
}
int pid = 0;
int *status = 0;
char * filename = node->redirect.target; // filename
int fd;
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
if((pid = fork()) == 0){
dup2(fd, input); // STDIN OR STDOUT
close(fd);
node_t* node2 = node->redirect.child;
execvp(node2->command.program, node2->command.argv); // execute program
printf("failed to execvp\n");
exit(1);
} else {
wait(status);
}
}
我是fork()
新手,但是我的问题是,在这里重定向stdout可以正常工作,但stdin却没有将任何内容写入给定文件,这是我做错了什么。
如注释中所述,您需要使用不同的打开选项,具体取决于您是打开文件进行输入重定向还是输出重定向。 您可以将其放入if
。
int flags;
if(node->redirect.mode == 2){
input = 1; // >
flags = O_WRONLY | O_CREAT | O_TRUNC;
} else{
input = 0; // <
flags = O_RDONLY;
}
int pid = 0;
int *status = 0;
char * filename = node->redirect.target; // filename
int fd;
fd = open(filename, flags, 0666);
另外,您需要为创建输出文件的情况指定权限模式。 可以一直指定此参数,当O_CREAT
不在标志中时,它将被忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.