【问题标题】:Executing shell commands with execvp()使用 execvp() 执行 shell 命令
【发布时间】:2015-02-13 23:58:40
【问题描述】:

我想编写一个类似于 Linux shell 的程序。我开始编写一个小程序来执行“ls”命令。我想不通的是我应该如何进行才能让我的程序像 shell 一样响应任何命令。 (例如 cat、cd、dir)。

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#define MAX 32
using namespace std;

int main() {
    pid_t c; 
    char s[MAX];
    int fd[2];
    int n;

    pipe(fd);
    c = fork();

    if(c == 0) {
        close(fd[0]);
        dup2(fd[1], 1);
        execlp("ls", "ls", "-l", NULL);
        return 0;
    } else {
        close(fd[1]);
        while( (n = read(fd[0], s, MAX-1)) > 0 ) {
            s[n] = '\0';
            cout<<s;
        }
        close(fd[0]);
        return 0;
    }

    return 0;
}

如何让我的程序读取用户输入的内容并将其传递给execlp(或类似的东西)?

【问题讨论】:

  • "... 让我的程序响应任何命令..." 在父进程中,您有 fd[1] 文件描述符,您可以使用它来编写关于已建立的pipe() 的东西。请注意,您列出的命令不需要任何输入交互。

标签: c++ linux shell command


【解决方案1】:

如果我正确理解了一个问题,您可以:

  • scanf()读取字符串数组
  • 使用execvp() 将其作为命令运行(它的工作方式与execlp() 相同,但您可以将所有参数作为数组传递)。

类似:

char args[100][50];
int nargs = 0;
while( scanf( " %s ", args[nargs] ) )
   nargs++;
args[nargs] = NULL;
/* fork here *
...
/* child process */
execvp( args[0], args );

【讨论】:

    【解决方案2】:

    一个外壳基本上做了以下事情:

    1. 从标准输入读取一行
    2. 解析该行以生成单词列表
    3. 分叉
    4. 然后shell(父进程)一直等到子进程结束,而子进程执行从输入行中提取的单词列表所代表的命令代码。
    5. shell 然后在第 1 步重新启动。

    首先构建一个非常简单的外壳。

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2023-03-18
      • 2018-10-06
      • 2016-05-01
      • 1970-01-01
      相关资源
      最近更新 更多