创建一个简单的 shell 我的 for 循环为每个要读入的单词创建一个单独的进程

标签 c linux shell

所以我正在尝试构建一个简单的 shell,当我执行下面的代码时,它将 for 循环中的每个循环都视为一个单独的进程,我不确定为什么。

问题:

1) 当我使用 for 循环追加要从 scanf() 读入的每个单词时,程序将每个单词视为一个单独的进程。我认为这与 wait() 有关,但我该如何解决?

2) 那为什么要这样做呢?

3) 然后在尝试退出时我必须为每个新的子进程键入 exit,这与问题 1 相关还是单独的问题?

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

int main(){
int  end = 1;
char *argv[100];
char progpath[30];
char *path = "/bin/";
pid_t pid;
int loop = 0;

while(1 && end !=0){ //while process has no error and user did't type exit
  int argc=0;
  printf("user>>> ");    //user input
  scanf("%s",string);
  if(strcmp(string,"exit") == 0){   // exits process when user types "exit"
    end = 0;
    exit(0);
  }

  char *token;
  token = strtok(string," ");
  while(token != NULL){
    argv[argc] = token;
    token = strtok(NULL," ");
    argc++;
  }
  argv[argc] = NULL;


  int i;
  for(i = 0; i<argc;i++){
    printf("\n%s\n",argv[i]);
  }

  strcpy(progpath,path);
  strcat(progpath,argv[0]);


  int pid = fork();
  if(pid == 0){
    if(end == 0){
      exit(0);
    }
    else{
      execv(progpath,argv);
      fprintf(stderr, "child could not exicute\n");
    }
  }

  else{
    wait(NULL);
    }
  }
  loop++;



}
return(0);
}

这是一个输出示例:

user>>> ls -l

ls
ages.c.save  Desktop       hlepshell    OperatingSystems   shell
a.out        Documents     infile.txt   OS hw1         shell.c
arrays.c~    Downloads     makefile~    OS hw1 errors.odt  shell.c~
bfgminer     hello.html    Music        Pictures           shell.tar.gz
bin      helpshell     newshell     Public         Templates
classScraper.py  helpshell.c   newshell.c   python_games       Videos
cs235        helpshell.c~  newshell.c~  scheduler.py
user>>> 
-l
child could not exicute
user>>> hello world

hello
child could not exicute
user>>> 
world
child could not exicute
user>>> exit
user>>> exit
user>>> 
world
child could not exicute
user>>> exit
user>>> exit
user>>> exit
*program ends*

最佳答案

这里:

    scanf("%s",string);

您从标准输入中读取了一个以空格分隔 的字符串到数组string 中。您稍后尝试在空格处标记该字符串,但其中肯定没有任何空格。这只是一个词,您最终最终将其视为一个完整的命令。稍后,您返回,阅读下一个单词,并给予相同的处理。您的程序完全按照您的指示执行。

如果您想一次读取整行,那么我推荐使用 fgets()getline()。后者自 2008 年起由 POSIX 标准化,但不是 C 标准的一部分。

关于创建一个简单的 shell 我的 for 循环为每个要读入的单词创建一个单独的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088733/

相关文章:

bash - 如何在bash中触发多个远程Shell脚本并发运行,然后等待它们完成?

c++ - 如何在两个 Lua 脚本之间共享数据

c - 为什么free不释放内存?

java - 更改操作系统时区不会更改 JVM 默认时区

python - 什么是 Linux 下软实时数据采集的良好存储候选者?

linux - 是否存在公开可用的部分解决方案来解析 *nix 样式的命令行选项而无需预先了解 key ?

c++ - 读取 fifo : why is it blocking then non-blocking

c - 在管道图中,数据危险的数据转发如何工作

regex - 将包含子字符串 'foo' 的文件重命名为 'bar'

MongoDB - 无权执行命令