Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用execvp()执行shell命令_C++_Linux_Shell_Command - Fatal编程技术网

C++ 使用execvp()执行shell命令

C++ 使用execvp()执行shell命令,c++,linux,shell,command,C++,Linux,Shell,Command,我想写一个像Linux外壳一样的程序。我开始编写一个小程序来执行“ls”命令。我不明白的是,为了让我的程序像shell一样响应任何命令,我应该如何继续。(例如cat、cd、dir) #包括 #包括 #包括 #包括 #定义最大32 使用名称空间std; int main(){ pid_t c; 字符s[MAX]; int-fd[2]; int n; 管道(fd); c=fork(); 如果(c==0){ 关闭(fd[0]); dup2(fd[1],1); execlp(“ls”、“ls”、“-l”

我想写一个像Linux外壳一样的程序。我开始编写一个小程序来执行“ls”命令。我不明白的是,为了让我的程序像shell一样响应任何命令,我应该如何继续。(例如cat、cd、dir)

#包括
#包括
#包括
#包括
#定义最大32
使用名称空间std;
int main(){
pid_t c;
字符s[MAX];
int-fd[2];
int n;
管道(fd);
c=fork();
如果(c==0){
关闭(fd[0]);
dup2(fd[1],1);
execlp(“ls”、“ls”、“-l”、NULL);
返回0;
}否则{
关闭(fd[1]);
而((n=read(fd[0],s,MAX-1))>0){
s[n]='\0';

cout外壳基本上执行以下操作:

  • 从标准输入读取一行
  • 解析该行以生成单词列表
  • 叉子
  • 然后shell(父进程)等待子进程结束,而子进程执行从输入行提取的单词列表所表示的命令代码
  • 然后,shell在步骤1重新启动

  • 首先构造一个非常简单的shell。

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

    • 使用
      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 );
    
    “…要使我的程序响应任何命令…”在父进程中,您有
    fd[1]
    文件描述符,可用于在已建立的
    pipe()
    上写入内容。请注意,您列出的命令不需要任何输入交互。
    char args[100][50];
    int nargs = 0;
    while( scanf( " %s ", args[nargs] ) )
       nargs++;
    args[nargs] = NULL;
    /* fork here *
    ...
    /* child process */
    execvp( args[0], args );