使用execvp()执行shell命令

夜狂94:

我想写一个像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(或类似的操作相同的东西)?

Jean-BaptisteYunès:

Shell基本上执行以下操作:

  1. 从stdin读取一行
  2. 解析该行以制成单词列表
  3. 叉子
  4. 然后外壳程序(父进程)将一直等到子进程结束,而子进程执行以执行从输入行提取的单词列表所表示的命令代码。
  5. 然后,shell在步骤1重新启动。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章