所以我正在尝试构建一个简单的 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/