ユーザーからの入力を受け取るトークナイザーがあります。そこから、リダイレクトの可能性を調べるために ">" または "<" をスキャンしました。
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 ループ (シェル設計) をラップするコードのほんの一部に過ぎないことに注意してください。これを 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 > !!!!!----------------------------------------------------