c语言中我自己的shell中的分段错误(内核转储)
我正在尝试用c编写自己的简单shell。 当我在shell中键入命令(例如ls)时,我得到分段错误(内核转储)。 也许问题主要在辩论中 我找不到问题出在哪里c语言中我自己的shell中的分段错误(内核转储),c,linux,shell,C,Linux,Shell,我正在尝试用c编写自己的简单shell。 当我在shell中键入命令(例如ls)时,我得到分段错误(内核转储)。 也许问题主要在辩论中 我找不到问题出在哪里 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #define BUFFER_SIZE 512 char *readli
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#define BUFFER_SIZE 512
char *readline(void){
char* line;
if(!fgets(line, BUFFER_SIZE, stdin)){
exit;
}
size_t length=strlen(line);
if (line[length-1]== '\n'){
line[length-1]='\0';
}
if(strcmp(line, "exit") ==0){
exit;
}
return line;
}
char **split_line(char *line){
char* tokens[100];
char* token;
int i=0;
token=strtok(line," ");
while( token !=NULL){
tokens[i] = token;
token=strtok(NULL, " ");
}
tokens[i]=NULL;
return tokens;
}
int exec_line(char **args){
pid_t pid, wpid;
char path[40];
int status;
strcpy(path, "/bin/");
strcat(path, args[0]);
pid=fork();
if(pid==0){
if (execvp(path, args)== -1){
printf("Child process could not do execvp \n");
}
exit(EXIT_FAILURE);
}else{
do{
wpid=waitpid(pid, &status, WUNTRACED);
}while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
void lloop(void){
char *line;
char **args;
int status;
do{
printf("my_shell> ");
line=readline();
args=split_line(line);
status=exec_line(args);
free(line);
free(args);
}while(status);
}
int main(){
lloop();
return EXIT_SUCCESS;
}
#包括
#包括
#包括
#包括
#包括
#定义缓冲区大小512
字符*读线(无效){
字符*行;
如果(!fgets(行、缓冲区大小、标准输入)){
出口
}
尺寸/长度=标准长度(直线);
如果(行[length-1]='\n'){
行[length-1]='\0';
}
如果(strcmp(行,“退出”)==0){
出口
}
回流线;
}
字符**分割线(字符*线){
字符*标记[100];
字符*令牌;
int i=0;
令牌=strtok(第行“”);
while(令牌!=NULL){
代币[i]=代币;
令牌=strtok(空,“”);
}
令牌[i]=NULL;
归还代币;
}
int exec_行(字符**参数){
pid_t pid,wpid;
字符路径[40];
智力状态;
strcpy(路径“/bin/”);
strcat(路径,参数[0]);
pid=fork();
如果(pid==0){
if(execvp(路径,参数)=-1){
printf(“子进程无法执行execvp\n”);
}
退出(退出失败);
}否则{
做{
wpid=waitpid(pid和状态,WUNTRACED);
}而(!WIFEXITED(status)和&!WIFSIGNALED(status));
}
返回1;
}
无效lloop(无效){
字符*行;
字符**args;
智力状态;
做{
printf(“我的外壳>”);
line=readline();
args=分割线(线);
状态=执行行(args);
自由线;
免费(args);
}而(身份),;
}
int main(){
lloop();
返回退出成功;
}
问题1:您无法写入退出代码>而不是退出()代码>
问题2:在您编写的分割线函数中
while(令牌!=NULL){
代币[i]=代币;
token=strtok(NULL,“”;}
没有升级i
问题3:在您编写的执行行函数中strcat(路径,参数[0])代码>
当args
是指向“字符串”的指针,而不是真正的“字符串”时
问题4:不要在你没有给他一个malloc的指针上使用free
malloc函数还为_free _函数在保存的位置写入内容
这是一种未定义的行为。char*line;如果(!fgets(line,BUFFER_SIZE,stdin))…
未分配内存。。。撞车,你应该检查一下。或者学习如何退出代码>是一个语法错误。它需要类似于退出(退出失败)代码>这是你的代码吗?你所说的“没有升级i
”是什么意思?你的意思是i
从未递增以索引下一个数组元素吗?我的意思是没有i++