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

问题描述 投票:0回答:1

所以我正在尝试构建一个简单的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*
c linux shell
1个回答
1
投票

这里:

    scanf("%s",string);

你从标准输入读到一个以空格分隔的字符串到数组string。您稍后尝试在空格处对该字符串进行标记,但肯定不会有任何空格。这只是一个词,你最终会把它当作一个完整的命令。之后,你循环回来,阅读下一个单词,并给它相同的处理。你的程序正在完成你告诉它要做的事情。

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

© www.soinside.com 2019 - 2024. All rights reserved.