fork() を使用して UNIX シェルを作成する必要がある課題があります。これは正しく機能しています。ここで、ユーザー入力をチェックして、それが有効な UNIX コマンドかどうかを確認する必要があります。有効でない場合 (つまり、「1035813」)、ユーザーに有効なコマンドを入力するように指示する必要があります。
ユーザー入力をこのリスト内のすべての文字列と比較できるように、可能なすべての unix コマンドのリストを取得する方法はありますか? または、これを行う簡単な方法はありますか?
これを行う適切な方法は次のとおりです。
cdおそらく組み込みコマンドである必要があります。forkそしてやってみるexec。(execvp実際には、おそらくあなたが本当に望んでいるものです)。それでも問題が解決しない場合は、そのerrno理由を確認してください。例:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("usage: %s <program-to-run>\n", argv[0]);
return -1;
}
char* program = argv[1];
/* in this case we aren't passing any arguments to the program */
char* const args[] = { program, NULL };
printf("trying to run %s...\n", program);
pid_t pid = fork();
if (pid == -1) {
perror("failed to fork");
return -1;
}
if (pid == 0) {
/* child */
if (execvp(program, args) == -1) {
/* here errno is set. You can retrieve a message with either
* perror() or strerror()
*/
perror(program);
return -1;
}
} else {
/* parent */
int status;
waitpid(pid, &status, 0);
printf("%s exited with status %d\n", program, WEXITSTATUS(status));
}
}
の出力を確認できますwhich。で始まらない場合はwhich: no <1035813> in blah/blah、おそらくそのシステムのコマンドではありません。
それが組み込みコマンドであるかどうかを知りたい場合は、ヘルプを悪用する可能性があります。
if help $COMMAND >/dev/null || which $COMMAND >/dev/null
then echo "Valid Unix Command"
else
echo "Not a valid command"
fi
それを試してみてください。
if which $COMMAND
then echo "Valid Unix Command"
else
echo "Non valid Unix Command"
fi