在简单C shell中输入NULL值后循环
我正在尝试编写一个简单的C shell。我的问题是,我已经编写了程序,这样当用户输入空值时,我就可以让shell退出并停止运行。然而,在使用不同的外壳后,我意识到外壳会继续循环。有没有办法在不重写代码的情况下解决这个问题?我对C还是个新手在简单C shell中输入NULL值后循环,c,linux,shell,C,Linux,Shell,我正在尝试编写一个简单的C shell。我的问题是,我已经编写了程序,这样当用户输入空值时,我就可以让shell退出并停止运行。然而,在使用不同的外壳后,我意识到外壳会继续循环。有没有办法在不重写代码的情况下解决这个问题?我对C还是个新手 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_CMD_SIZE 512
int getPath(){
printf("PATH = %s\n", getenv("PATH"));
return 0;
}
int setPath(char* arg){
setenv("PATH", arg, 1);
return 0;
}
int setwd() {
char *arg;
arg = getenv("HOME");
chdir(arg);
return 0;
}
int main()
{
char buff[MAX_CMD_SIZE]; //buff used to hold commands the user will type in
char *defaultPath = getenv("PATH");
char *args[50] = {NULL};
char *arg;
int i;
pid_t pid;
setwd();
while(1){
printf(">");
if (fgets(buff, MAX_CMD_SIZE, stdin) == NULL) { //Will exit if no value is typed on pressing enter
setPath(defaultPath);
getPath();
exit(0);
}
arg = strtok(buff, " <|>\n\t");
i = 0;
if (arg == NULL) return -1;
while (arg != NULL){
printf("%s\n", arg);
args[i] = arg;
arg = strtok(NULL, " <|>\n\t");
i++;
}
if (strcmp(args[0], "exit") == 0 && !feof(stdin)){ //Will exit if input is equal to "exit" or ctrl + d
setPath(defaultPath);
getPath();
exit(0);
}
else {
pid = fork();
if (pid < 0){ //Error checking
fprintf(stderr, "Fork Failed\n");
} else if (pid == 0){ //This is the child procsess
execvp(args[0], args);
exit(-1);
} else { //Parent Process
wait(NULL); // Parent will wait for child to complete
}
}
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
#定义最大命令大小512
int getPath(){
printf(“路径=%s\n”,getenv(“路径”);
返回0;
}
int setPath(字符*arg){
setenv(“路径”,arg,1);
返回0;
}
int setwd(){
char*arg;
arg=getenv(“主页”);
chdir(arg);
返回0;
}
int main()
{
char buff[MAX_CMD_SIZE];//用于保存用户将键入的命令的buff
char*defaultPath=getenv(“路径”);
char*args[50]={NULL};
char*arg;
int i;
pid_t pid;
setwd();
而(1){
printf(“>”);
如果(fgets(buff,MAX_CMD_SIZE,stdin)=NULL){//如果按enter键时未键入值,则将退出
设置路径(默认路径);
getPath();
出口(0);
}
arg=strtok(buff,“\n\t”);
i=0;
if(arg==NULL)返回-1;
while(arg!=NULL){
printf(“%s\n”,arg);
args[i]=arg;
arg=strtok(空,“\n\t”);
i++;
}
如果(strcmp(args[0],“exit”)==0&&!feof(stdin)){//将在输入等于“exit”或ctrl+d时退出
设置路径(默认路径);
getPath();
出口(0);
}
否则{
pid=fork();
如果(pid<0){//错误检查
fprintf(stderr,“Fork失败\n”);
}else如果(pid==0){//这是子进程
execvp(args[0],args);
出口(-1);
}else{//父进程
等待(NULL);//父级将等待子级完成
}
}
}
返回0;
}
他们应该如何输入空值?你说的“空值”是指空字符串吗?大概他们的意思是如果fgets
返回空值,这表示EOF或读取错误。不,不需要重写代码就无法更改此值。:)诚实。你的意思是如果使用不输入任何字符串,那么它必须退出,对吗?所以,什么是错误的点击输入
您将退出该程序。