[英]Unix shell: how do I check user input to see if it's a valid unix command?
我有一個作業,需要使用fork()創建一個UNIX shell。 我的工作正常。 現在,我需要檢查用戶輸入以查看它是否是有效的unix命令。 如果它無效(即其“ 1035813”),則需要告訴用戶輸入有效命令。
有沒有一種方法可以獲取每個可能的unix命令的列表,以便可以將用戶輸入與該列表中的每個字符串進行比較? 還是有更簡單的方法來做到這一點?
您可以檢查的輸出which
。 如果不是以以下which: no <1035813> in blah/blah
開頭which: no <1035813> in blah/blah
則可能不是該系統上的命令。
適當的方法是:
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));
}
}
試試看
if which $COMMAND
then echo "Valid Unix Command"
else
echo "Non valid Unix Command"
fi
如果您想找出它是否是內置命令,則可以濫用幫助:
if help $COMMAND >/dev/null || which $COMMAND >/dev/null
then echo "Valid Unix Command"
else
echo "Not a valid command"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.