[英]Unix shell: how do I check user input to see if it's a valid unix command?
I have an assignment in which I need to create a unix shell using fork(). 我有一个作业,需要使用fork()创建一个UNIX shell。 I've got this working correctly. 我的工作正常。 Now I need to check user input to see if it is a valid unix command. 现在,我需要检查用户输入以查看它是否是有效的unix命令。 If it is not valid (ie its "1035813") I need to tell the user to enter a valid command. 如果它无效(即其“ 1035813”),则需要告诉用户输入有效命令。
Is there a way I can get a list of every possible unix command so I can compare the user input with every string in this list? 有没有一种方法可以获取每个可能的unix命令的列表,以便可以将用户输入与该列表中的每个字符串进行比较? Or is there an easier way to do this? 还是有更简单的方法来做到这一点?
You could check the output of which
. 您可以检查的输出which
。 If it doesn't start with which: no <1035813> in blah/blah
then it's probably not a command on that system. 如果不是以以下which: no <1035813> in blah/blah
开头which: no <1035813> in blah/blah
则可能不是该系统上的命令。
The appropriate way to do this is: 适当的方法是:
cd
should probably be a built in command. 例如, cd
可能应该是内置命令。 fork
and try to exec
it. fork
并尝试exec
它。 ( execvp
is probably what you really want, actually). (实际上, execvp
可能就是您真正想要的)。 If that fails, check errno
to determine why. 如果失败,请检查errno
以确定原因。 Example: 例:
#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));
}
}
Try that. 试试看
if which $COMMAND
then echo "Valid Unix Command"
else
echo "Non valid Unix Command"
fi
If you'd like to find out, whether it is a builtin command, you could abuse help: 如果您想找出它是否是内置命令,则可以滥用帮助:
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.