shell - 我正在尝试编写一个 shell 程序来一次执行多个命令

标签 shell c

我的代码

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

int main() 
{ 

char * arg_list[3];
arg_list[0] = "ls";
arg_list[1] = "-l";
arg_list[2] = 0;

char *arg_list2[3];
arg_list2[0] = " ps";
arg_list2[1] = "-ef";
arg_list2[2] = 0;

    for(int i=0;i<5;i++){ // loop will run n times (n=5) 

       if(fork() == 0) { 
    if (i == 0){
    execvp("ls", arg_list);
}else if(i==1){
execvp("ps" , arg_list2);
}else if(i>1){
           printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid()); 
        exit(0); 
}
      } 
    } 
    for(int i=0;i<5;i++) // loop will run n times (n=5) 
           wait(NULL); 

} 

我正在尝试修改它

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

int main() 
{ 
    for(int i=0;i<5;i++){ // loop will run n times (n=5) 

       if(fork() == 0) { 
           printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid()); 
        execlp(argv[i],argv[i],argv[i+1],(char*)NULL);
        exit(0); 
      } 
    } 
    for(int i=0;i<5;i++) // loop will run n times (n=5) 
           wait(NULL); 

} 

-- 需要指导和理解

我正在尝试制作自己的小 shell 程序。当我运行第一个代码时工作正常,在命令行上运行所有命令。但我无法知道和定义用户可能输入的所有命令。所以我试图获取一个基本代码,它可以运行用户输入的单个或多个命令。我尝试使用 execlp ,但它无法编译,说 argv 未定义,这是真的,因为我不想专门定义它。

最佳答案

I am trying to make my own tiny little shell program. When I run my first code works fine, runs all commands on the command line. But I cannot know and define all commands the user might enter.

当然...... shell 程序的目的基本上是:

  1. 读取用户输入
  2. 执行用户输入
  3. 返回执行结果。

您的代码中没有任何内容可以读取用户输入......

So i am trying to get a base code which could run any commands single or multiple entered by user.

所以读取用户输入;-)

I tried using execlp where it does not compile saying argv is not defined which is true as i don't want to specifically define it.

当然...但是 GCC 如何猜测 `argv[]̀ 必须自动填充用户输入? 用 C 语言编码时没有什么是自动的。您必须手动管理它。

另外,请注意 argc , argvenvp通常保留给 main()功能:

main(int argc, char **argv, char **envp)

所以你可以使用其他东西来构建你的命令数组。

在伪代码中,您必须实现的是:

quit=0
while (quit = 0) {
    command_to_run = read_user_input();
    if (command_to_run == "exit") {
       quit = 1;
    } else {
       execute(command_to_run);
    }
}

一些建议:

  • 尝试使用更多功能。例如,实现 fork_and_run(char **cmd)函数来 fork 然后执行用户提供的命令。 Il 将使您的代码更具可读性且易于维护。

  • 仔细阅读手册页:您应该知道的所有内容(例如,提供给 execvp() 的数组必须以 NULL 结尾)都写在其中。

  • 您的调试消息应打印到 stderr 。命令运行的结果必须打印到 stdin ,所以使用fprintf()而不是printf()写入正确的流。

  • 我会使用 #define debug(x) fprintf(stderr, x)或类似的调试输出,以便您稍后可以轻松禁用;-)

关于shell - 我正在尝试编写一个 shell 程序来一次执行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58908912/

相关文章:

c - 局部结构和指针

c - 可变长度参数如何在 C 中工作?

c - sleep 函数是让所有线程都 sleep 还是只让调用它的线程 sleep ?

c - 无向图 -> 深度优先搜索 C 编程 - 计算连接组件的数量

shell - 如何获取两个 S3 存储桶之间的文件差异?

mysql - 如何使用脚本shell执行mysql命令

linux - 如何将输出通过管道传输到 stdout 并传输到 docker 中的另一个进程

linux - 如何在一行中过滤 shell 脚本中的多个扩展名?

linux - 如何递归列出所有文件和目录

c - 在 C 中声明具有可变大小的全局结构变量