c - 获取用户输入,然后执行 execvp

标签 c unix strtok

所以我有以下 C 代码,要求用户给出一个命令(在 unix 中有效),然后我必须获取该字符串并将其拆分为一个数组,以便执行用户使用 execvp 给出的命令()。它可以编译,但 execvp 似乎不起作用。我在数组中分割用户输入的方式有问题吗? PS:有些内容不是必需的,但这不是最终的程序。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>

main() {

  char str[64];
  int i =0;
  char *p = strtok(str," ");

  printf("Please give me a Unix command! :\n");
  gets(str);
  char  *array[sizeof(str)];
  while (p!=NULL) {
    array[i++] = p;
    p = strtok (NULL, " ");
  }

execvp(str ,array);
perror("execvp");
}

运行时得到的输出是:

Please give me a Unix command! :
ls -l
execvp: No such file or directory

最佳答案

您在 str 获得任何信息之前调用 strtok(str, "")

在获得输入后简单地调用它:

main() {
  char str[64];
  char *array[sizeof(str)];
  char *p = NULL;
  int i = 0;

  printf("Please give me a Unix command! :\n");
  fgets(str, sizeof(str), stdin);  // Use fgets instead of gets.

  p = strtok(str," ");

  while (p != NULL) {
    array[i++] = p;
    p = strtok(NULL, " ");
  }

  execvp(str, array);
}

关于c - 获取用户输入,然后执行 execvp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639210/

相关文章:

c - C 中的函数需要有类型吗?

调用带参数的 perl 例程

c - 两个数组相加

linux - 2 个或更多 fork 系统调用如何工作?

在 C 中将 char * 转换为大写

c - 如何使用 fgets 和 strtok 获取多个输入?

c++ - va_arg 带有 void* 列表

linux - Shell 脚本钻石

shell - 在shell脚本中打印文件时间

C - 将带有重复分隔符字符的字符串拆分为 2 个子字符串