私のコードを以下に貼り付けます。
出力をファイルにリダイレクトするために dup2 を使用しようとしています。
リダイレクトに使用すると(コメントを削除すると)正常に動作し、標準出力ではなくファイルに出力されます。例: ls > test 、結果として ls が test に出力されます。
問題は、 > なしの ls では何も出力されないことです。リダイレクトする機能はありませんが、コメント ls 出力をそのままにしておきます。
redirect[0] は < または > のいずれかであるか、何も指定されていません。 redirect[1] はリダイレクト先のファイルのパスです。
コマンドは、コマンドのpicesを含むcstringの配列です コマンドも同様です
コードをコメントした出力例
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1> ls
a.out myshell.c myshell.c~
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1>
コードのコメントを外して
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1> ls
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1>
/*
if (!strcmp(redirect[0],">")){
if ((fd = open(redirect[1], O_RDWR | O_CREAT)) != -1)
dup2(fd, STDOUT_FILENO);
close(fd);
}
*/
if (command[0][0] == '/'){
int c = execv(command[0], commands);
if (c != 0){
printf("ERROR: command does not exist at path specified\n");
exit(0);
}
}
else if (!execv(path, commands)){
exit(0);
}