【发布时间】:2016-09-11 22:43:16
【问题描述】:
我已经编写了一个简单 shell 的开头,到目前为止 'ls' 工作正常。我为分叉和执行编写了这段代码。 但是,当我尝试使用重定向时,我收到错误“无法访问'>':没有这样的文件或目录。 如何让这些运算符这样读取?
int startProcess (StringArray sa)
{
int pid;
int status;
int fd1;
int fd2;
int current_in;
int current_out;
switch( pid = fork()){
case -1://This is an error
perror("Failure of child.");
return 1;
case 0: // This is the child
execvp(sa[0], sa);
for (int i = 0; i < strlen(sa); i++){
if (sa[i] == '|'){
}
if (sa[i] == '>'){
fd1 = creat(sa[i-1], 0644);
dup2(fd1, STDOUT_FILENO);
close(fd1);
}
if(sa[i] == '<'){
fd2 = open(sa[i-1], O_RDONLY, 0);
dup2(fd2, STDIN_FILENO);
close(fd2);
}
}
perror(sa[0]);
printf("Could not execute '%s'\n", sa[0]);
exit(1);
default:// This is the parent
wait(&status);
return (status == 0) ? 0: 1;
}
}
【问题讨论】:
-
用
sa[i + 1]替换creat和open中的sa[i - 1] -
呃...你为什么要执行 before 设置重定向?
-
在 sa 上调用 strlen 也意味着 sa 实际上是
char *... 这没有多大意义。 -
当然您需要不将重定向“令牌”传递给您正在执行的程序。
标签: c shell redirect pipe fork