我有一个接受用户输入的分词器。从那里我继续扫描“>”或“<”以寻找潜在的重定向。
for(i=0;i<n;i++){ //I/O redirection
//printf("extracted token is %s\n",tokens[i]);
//get the
if (strcmp(tokens[i],"<")==0) {
printf("found < !!!!\n");
if(tokens[i+1] == NULL){ //if there isn't a input file
printf("Please have a input file\n");
break;
}else if(tokens[i-1] == NULL){ //if there isn't a output file
printf("Pleae have a output file\n");
break;
}
infile = 1;
outfile = 1;
fd=fopen(tokens[i-1],"w");
fclose(fd);
}
}
上面的代码只处理“<”重定向。请注意,这只是围绕 while 循环(shell 设计)的一小段代码。在它通过这个for循环之后,我有这个:
for(i=0;i<n;i++){
//printf("extracted token is %s\n",tokens[i]);
char *ex = "exit";
char *his = "history";
if(strcmp(tokens[0],his) == 0 && max_cmd == 0 ){ //get history
for(j=0;j<counter;j++){
printf("%i. %s\n",j+1,historic_cmd[j]);
}
}else if(strcmp(tokens[0], his) ==0 && max_cmd == 1){
for(j=0; j<CMD_MAX;j++){
printf("%i. %s\n",j+1,historic_cmd[j]);
}
}else if(strcmp(tokens[0],ex) == 0){ //exit program
exit(2);
}else{ //forking
pid = fork();
if(pid){
pid=wait(NULL);
if(infile > 0)
dup2(fileno(fd),0);
if(outfile > 0)
dup2(fileno(fd),1);
}else{
if(execvp(tokens[0],tokens)){
puts(strerror(errno));
exit(127);
}
}
}
} // end of for loop
}//end of while loop for user input
我对它为什么不执行重定向感到困惑。如果我输入以下内容:
ps > s
它在工作目录中创建文件 s,但它是空的。我是否错误地使用了“dup2”?
“ps > s”的示例输出:
user$>ps > s
ps: illegal option -- >
usage: ps [-AaCcEefhjlMmrSTvwXx] [-O fmt | -o fmt] [-G gid[,gid...]]
[-u]
[-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]
ps [-L]
ps: illegal option -- >
usage: ps [-AaCcEefhjlMmrSTvwXx] [-O fmt | -o fmt] [-G gid[,gid...]]
[-u]
[-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]
ps [-L]
ps: illegal option -- >
usage: ps [-AaCcEefhjlMmrSTvwXx] [-O fmt | -o fmt] [-G gid[,gid...]]
[-u]
[-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]
ps [-L]
found > !!!!!----------------------------------------------------