c - 在 C 中使用 execvp 执行单独的命令

标签 c linux shell unix exec

我已经将来自用户的给定命令分成子字符串,这是代码:

     int i;

     char *line = malloc(BUFFER);
     char *origLine = line;
     fgets(line, 128, stdin);   // get a line from stdin


     // get complete diagnostics on the given string

     lineData info = runDiagnostics(line);

     char command[20];
     sscanf(line, "%20s ", command);
     line = strchr(line, ' ');

     printf("The Command is: %s\n", command);

     int currentCount = 0;                  // number of elements in the line
     int *argumentsCount = &currentCount;   // pointer to that


     // get the elements separated

     char** arguments = separateLineGetElements(line,argumentsCount);


     // here we call a method that would execute the commands


    if (execvp(*arguments,*argumentsCount)  < 0)       // execute the command
    {
                printf("ERROR: exec failed\n");
                exit(1);
    }

当我在 execvp(*arguments,*argumentsCount) 中执行命令时,它失败了。

怎么了?

谢谢。

编辑:

来自用户的输入是:ls > a.out,因此我有 3 个字符串,它们是:

ls>a.out,但失败了。

最佳答案

如果您不调用 shell,则 Shell 重定向将不起作用。 您也不会通过路径搜索来查找 ls 程序。 一些选项

  • 改用 system(),返回时退出

  • 执行一个 shell 并让它运行你的命令

  • 像 shell 一样设置重定向,然后 fork 并执行每个所需的子程序。

此外,您的命令没有多大意义,您可能想要 ¦ 而不是 >,如果 a.out 不在您的路径中,则可能需要指定它的目录。也考虑给它起一个有意义的名字。

关于c - 在 C 中使用 execvp 执行单独的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667332/

相关文章:

c++ - 编译我的代码以通过 xcode 在 OSX 中使用 mongodb c 驱动程序

PHP:如何检测用户是否是 root/sudo?

bash - 如何将 shell 从 bash 更改为 dash

linux - 将三个 echo 语句的输出通过管道传递到邮件

php - 通过 php 用户在 root 上管理 Linux screen

c - 分割字符串函数的段错误

c - 使用 sscanf() 拆分 AT 命令字符串

c - 为什么我们在调用bind()时将sockaddr_in转换为sockaddr?

linux - 从分隔文件中提取特定列(长行到下一行)

c - 使用指针下标整数变量