繁体   English   中英

Unix Shell:如何检查用户输入以查看它是否是有效的Unix命令?

[英]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则可能不是该系统上的命令。

适当的方法是:

  1. 检查它是否是您的Shell中的内置命令。 例如, cd可能应该是内置命令。
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM