我正在尝试用C语言为Linux创建一个基本的类似shell的程序,但我遇到了一些问题。我在我创建的parse_cmdline
函数中的某个地方遇到了分段错误,但我预计参数= parse_cmdline (cmdline);可能不是实现我想要做的事情的最佳方法。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
char** parse_cmdline(const char *cmdline){
char** input;
int counter = 0;
char* token;
token = strtok(cmdline);
int tokenlen = strlen(token);
input = realloc(input , sizeof(char*)+tokenlen*sizeof(char));
input[counter] = token;
while( token != NULL ) {
token = strtok(NULL, " ");
printf("%s\n",token);
tokenlen = strlen(token);
input = realloc(input , sizeof(char*)+tokenlen*sizeof(char));
counter++;
input[counter] = token;
}
return input;
}
int main(){
char* cmdline = NULL;
size_t cmdlength = 0 ;
char** arguments;
int status;
pid_t pid;
while (1){
getline(&cmdline , &cmdlength , stdin);
arguments = parse_cmdline(cmdline);
pid = fork();
if(pid == 0){
if(access(arguments[0], F_OK) == 0 ) {
if(access(arguments[0], X_OK)){
execv(arguments[0],arguments);
exit(0);
} else {
printf("%s: Permission denied",arguments[0]);
exit(-1);
}
} else {
printf("%s: No such file or directory",arguments[0]);
exit(-1);
}
} else {
waitpid(-1, &status, 0);
}
free(arguments);
cmdline = NULL ;
cmdlength = 0 ;
}
return 0;
}
发布于 2020-12-20 13:43:58
有两个问题立即跳到我的脑海中:
strtok()
是破坏性的,所以不应该将const char *
作为它的第一个参数。你的编译器至少应该对此进行警告。不要忽视编译器的警告,特别是在你寻找bug的时候。如果您对parse_cmdline()
修改字符串没有意见,那么就从它的参数中删除const
(而且不要将const
数据传递给函数)。如果不希望修改输入数据,则创建本地非const
副本或使用strtok()
.以外的其他内容
当没有更多的令牌时,
strtok()
返回NULL
,但是您在没有对其进行测试的情况下使用了它的结果。无论是对于初始strtok()
调用还是对于循环中的调用,while
条件中的null检查都为时已晚。https://stackoverflow.com/questions/65380369
复制相似问题