分割故障(核心转储)在我自己的shell中c
我想在c中编写我自己的简单shell。 当我在shell中输入一个命令(例如ls)时,我得到分段错误(核心转储)。 也许问题出在主要的争论中?分割故障(核心转储)在我自己的shell中c
我找不到问题所在。
#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;
}
问题1:你不能写的exit();
exit;
代替
问题2:在分割线功能你写
while(token !=NULL){ tokens[i] = token; token=strtok(NULL, " ");}
不提倡i
问题3:在exec_line功能你写strcat(path, args[0]);
时args
是一个指向 '串',而不是一个真正的 '字符串'。
问题4:上,你没有给他一个的malloc的指针从来不使用免费。
the malloc函数还在保存的地方写了_free _function的东西。
这是一个未定义的行为。
你是什么意思“没有宣传'我'”?你的意思是'i'从来没有增加索引下一个数组元素? –
我的意思是没有'i ++' –
'char * line;如果(!fgets(line,BUFFER_SIZE,stdin))...'没有分配内存......崩溃。 –
你应该看看[适当的C格式化](// prohackr112.tk/pcf)。或者学习如何[彻底混淆你的代码](// prohackr112.tk/guide/coding/proper-c-obfuscation)。 –
顺便说一句'exit;'是一个语法错误。它需要像'exit(EXIT_FAILURE);'这是你的代码吗? –